简体   繁体   中英

How to remove carriage return in python on eclipse IDE

I want to write a file by copying the contents of another file that has '\\r' at the end of every line. I want to remove '\\r' while writing to new file

file 1 (source)

input

input

output

file 2 (destination)

input

input

output

rf = open("file 1", 'r')
wf = open("file 2", 'w')
for line in rf:
    line = line.rstrip('\r')
    wf.write(line)

I tried the above code, but it didnt work. Please help

From the doc for open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) :

When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\\n', '\\r', or '\\r\\n', and these are translated into '\\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

So call open("file 1", 'r', newline='\\n') .

Guys I was able to solve the problem, The main thing we need to do is while reading and writing, it should be in "rb" other wise it wont work.

rf = open("file1", "rb").read()
newdata = rf.replace("\r\n","\n")
if newdata != rf:
    wf = open("file2", 'wb')
    wf.write(newdata)
    wf.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM