Using Python to replace "\ r \ r \ n" with "\ r \ n" in a binary

I am very new to Python and just working my way out to complete the task, and would appreciate help (Python 3.1).

I have a CSV file written with DictWriter with an excel dialect. After creating the file, I notice additional lines in the file and upon closer inspection, because I have "\ r \ r \ n" at the end of each line, and not "\ r \ n".

I could solve this one of two ways:

  • Open the file in binary mode instead of text. The problem is that for my life I can’t figure out how to make writerow () work against a binary file - I get a ton of exceptions.

  • The second (simpler) solution simply replaces all "\ r \ r \ n" with "\ r \ n".

However, in my attempts, I came across these errors:

and. At first we don’t close the file, and the search and replace just add even more lines "\ r \ r \ n". b. I tried to close the file first, re-open in binary mode and do the same search and replace, but I get the message and error:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process

Here is the code:

#code before this writes to the final in text mode
myfile.close()
myfile = open(outputFile, "wb")
for line in fileinput.FileInput(outputFile, inplace=1):
    line = line.replace("\r\r\n", "\r\n")
    print (line)
myfile.close()

Bring any help anyone can provide!

+3
source share
5 answers

( , ) - , , , . . " , " , Windows , .

- gulp, (gigabyte-plus):

with open(filename, 'rb') as f:
  data = f.read()
with open(newfilename, 'wb') as f:
  f.write(data.replace('\r\r\n', '\r\n'))
os.unlink(filename)
os.rename(newfilename, filename)

- " " .

Python 3.1 bytes , , . , , write

  f.write(data.replace(b'\r\r\n', b'\r\n'))

b Python, bytes, str.

+4

, , \r\r\n, , Windows , .

, Python 2 CSV Windows

+1

:

fileR = open(outputFile, "r")
text = fileR.read().replace("\r\r\n", "\r\n")
fileR.close()
fileW = open(outputFile, "wb")
fileW.write(text)
fileW.close()
0

I am not very good at special cases of file processing. However, since you mentioned that you are dealing with a CSV file (which can be opened with excel), I would recommend looking into pyExcelerator .

Hope this helps

0
source

To write CSV files correctly, and not fix them after the fact, see this question: Python3: writing csv files

0
source

Source: https://habr.com/ru/post/1735536/


All Articles