在Windows中,如果我使用Python的"for line In file“语法来读取普通文本文件的内容,最后一行将不会以换行符结尾,而是以前面的所有行结尾。在Linux中,这种行为似乎是不同的--当我逐行读取文件并打印其内容时,我总是发现最后一行以换行符结尾,即使实际文件中不存在这样的字符!我还尝试使用file.readline()函数,结果是相同的。
(我假设文本文件实际上没有以换行符结尾。如果是这样的话,Linux就会从文件的末尾打印两行新行,而不是只打印真正存在的行。)
我的代码很简单。问题是,它在Linux中产生的结果与在Windows中产生的结果不同。
with open(path, 'r') as file:
for line in file:
print('>', line, '<', sep='')
'''
# Alternate method:
while True:
line = file.readline()
if not line:
break
print('>', line, '<', sep='')
'''在Linux上(确切地说,Ubuntu13.10),最后一行总是以幻影换行符结尾。我试过Python 2和3。知道这里发生了什么吗?
发布于 2014-09-01 00:13:57
Linux中的每个文本文件都由一系列行和一个终止的新行字符组成。如果一个文件在linux中没有以新的行字符结尾,那么它就不被视为文本文件。这是在linux使用的POSIX文件系统中定义的。
3.206 Line
A sequence of zero or more non- <newline> characters plus a terminating <newline> character.因此,这不是您的代码的问题。它只是linux下的文件系统。您可以简单地删除从文件中读取的字符串中的终止换行符。
发布于 2014-09-01 00:03:48
删除断线怎么样?这是你想要的吗?
with open('/Users/sebastian/Desktop/Untitled.txt', 'r') as file:
for line in file:
line = line.strip()
if line:
print('>', line, '<', sep='')版画
>This is the first line<
>this is the second line<
>this is the third line<PS:如果文本文件的中间有空行,您的备用方法就会有问题。
编辑
看看PEP278。“U”模式可能对您的情况有所帮助。
with open('/Users/sebastian/Desktop/Untitled.txt', 'rU') as file:
for line in file:
line = line.strip()
print('>', line, '<', sep='')版画
>This is the first line<
>this is the second line<
><
>this is the fourth line (blank line above)<
><或者,您可以添加一条特定于平台的额外行,例如
进口平台
if platform.system()=='Windows':
# do sth
else:
# do sthhttps://stackoverflow.com/questions/25597330
复制相似问题