Windows 与 Linux 文本文件读取 [英] Windows vs. Linux Text File Reading

查看:49
本文介绍了Windows 与 Linux 文本文件读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是问题所在,我最近从 Windows 切换到 Ubuntu,我的一些用于分析数据文件的 python 脚本给了我错误,我不确定如何正确解决.

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:

[标题]

关于仪器等的各种信息

[数据]

状态、代码、温度、场等........

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

0,0,300、0.013 等...

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

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

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

此代码在 Windows 中运行良好,但在 Ubuntu 中,i 的值始终采用特定数据文件中的总行数.所以我知道问题是处理[Data]\n"线.感谢您的帮助.

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.

推荐答案

如果您以默认文本模式打开文件,在 Windows 上,\r\n 会在读取时转换为 \n.在 Linux 上这不会发生.您的数据文件可能包含 \r\n,尤其是在 Windows 上创建时.改用通用换行模式:

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')

这篇关于Windows 与 Linux 文本文件读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆