gpt4 book ai didi

python - 使用回车遍历文件

转载 作者:太空狗 更新时间:2023-10-29 18:00:31 26 4
gpt4 key购买 nike

有没有一种方法可以使用语法遍历文本文件,

with open(filename,'r') as f:
for line in f:
print f

如果文件只包含回车符而没有换行符?

目前我能做的就是

with open(filename,'r') as f:
for line in f.read().split('\r'):
print f

但是文件有时会很大。我不想使用 dos2unix 修改文件,因为另一个软件程序需要它的原始格式。

最佳答案

您可以使用 Python 的 universal newline support for open()

In addition to the standard fopen() values mode may be 'U' or 'rU'. Python is usually built with universal newline support; supplying 'U' opens the file as a text file, but lines may be terminated by any of the following: the Unix end-of-line convention '\n', the Macintosh convention '\r', or the Windows convention '\r\n'. All of these external representations are seen as '\n' by the Python program. If Python is built without universal newline support a mode with 'U' is the same as normal text mode. Note that file objects so opened also have an attribute called newlines which has a value of None (if no newlines have yet been seen), '\n', '\r', '\r\n', or a tuple containing all the newline types seen.

关于python - 使用回车遍历文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5174243/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com