Windows vs. Linux Text File Reading

2019-09-14 07:20发布

问题:

Here is the issue, I have recently switched from Windows to Ubuntu and some of my python scripts for analyzing data files give me errors that I am unsure how to address correctly.

The data files from my current instrumentation output something that this:

[Header]

Various information w.r.t the instrument etc.

[Data]

Status,Code,Temperature,Field, etc.........

0,0,300, 0.013, etc...

So basically, this snippet of code is meant to read the data file and parse out all the information from [Header] to [Data] and start reading the real data at the appropriate lines regardless of how the header is arranged as different instruments have different headers.

f = open('file.dat')
lines = f.readlines()
i = 0
while (lines[i]!="[Data]\n"):
    i+=1
i = i + 2

This code runs fine in Windows, but in Ubuntu, the value of i always takes on the total number of line in the particular data file. So I know the issue is the handling of the "[Data]\n" line. Thanks for any help.

回答1:

If you open a file in default text mode, on Windows \r\n is translated to \n when read. On Linux this doesn't happen. Your data file likely has \r\n especially if created on Windows. Use Universal newline mode instead:

open(filename, 'rU')