Why the same file read and writing python program result in different result in linux and windows?

45 views Asked by At

Here is my python program, they all generate the .object file, but my software only successfully load the file regenerated by windows, not the linux.

file_path = 'D:\\xxx\\batch_sim_scene\\base\\CubeMoving.object'
new_file_path = '.\\CubeMoving.object'

with open(file_path, 'r', encoding='utf-8') as file:
    lines = file.readlines()
file.close()
 
with open(new_file_path, 'w', encoding='utf-8') as file:
    for i in range(len(lines)):
        file.writelines(lines[i])

I expect that the program works the same in linux as the windows, anyone can tell me what the problem is?

2

There are 2 answers

0
SIGHUP On BEST ANSWER

Looks like you have a plain line-oriented text file that you want to copy from one place to another.

The confusion in your code comes from not understanding what readlines() and readline() do with respect to the line termination sequence - either '\n' or '\r\n'

If you want to do this line by line (which may be important due to file size) then:

ENC = 'utf-8'

with open(file_path, 'r', encoding=ENC) as f, open(new_file_path, 'w', encoding=ENC) as w:
    for line in f:
        w.write(line)
1
ZHIHA On
with open(file_path, 'r', encoding='utf-8') as file:
    lines = file.readlines()
file.close()
 
with open(new_file_path, 'w', encoding='utf-8', newline='\n') as file:
    for line in lines:
        file.write(line.rstrip('\n') + '\r\n')

the problem is that in linux newline is '\n', but in window new line is '\r\n'