简体   繁体   English

Windows 与 Linux 文本文件读取

[英]Windows vs. Linux Text File Reading

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.问题是,我最近从 Windows 切换到 Ubuntu,我的一些用于分析数据文件的 python 脚本给了我错误,我不确定如何正确解决。

The data files from my current instrumentation output something that this:我当前仪器的数据文件输出如下内容:

[Header] [标题]

Various information wrt the instrument etc.各种信息wrt仪器等。

[Data] [数据]

Status,Code,Temperature,Field, etc.........状态、代码、温度、场等.........

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

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.所以基本上,这段代码是为了读取数据文件并解析出从 [Header] 到 [Data] 的所有信息,并在适当的行开始读取真实数据,而不管标题如何排列,因为不同的仪器有不同的标题。

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.这段代码在 Windows 中运行良好,但在 Ubuntu 中, i的值总是取特定数据文件中的总行数。 So I know the issue is the handling of the "[Data]\\n" line.所以我知道问题在于“[Data]\\n”行的处理。 Thanks for any help.谢谢你的帮助。

If you open a file in default text mode, on Windows \\r\\n is translated to \\n when read.如果您以默认文本模式打开文件,则在 Windows 上,\\r\\n 会在读取时转换为 \\n。 On Linux this doesn't happen.在 Linux 上这不会发生。 Your data file likely has \\r\\n especially if created on Windows.您的数据文件可能包含 \\r\\n,尤其是在 Windows 上创建时。 Use Universal newline mode instead:改用通用换行模式:

open(filename, 'rU')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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