带有定制delimi的Python readline

2024-04-29 20:04:09 发布

您现在位置:Python中文网/ 问答频道 /正文

新手。 我试图从一个文件中读取行,但是.txt文件中的一行在中间某处有一个\n,当试图使用.read line python读取该行时,它会将其剪切在中间并输出为两行。

  • 当我把这一行复制到这个窗口时,它显示为两行。所以我把文件上传到这里:https://ufile.io/npt3n

  • 还添加了文本文件中显示的文件截图。

  • 这是Whatsup导出的群聊历史记录..如果您想知道的话。
  • 请帮助我完整地阅读一行,如txt文件所示。

是的。

f= open("f.txt",mode='r',encoding='utf8')

for i in range(4):
    lineText=f.readline()
    print(lineText)

f.close()

enter image description here


Tags: 文件httpsiotxtread历史记录modeline
2条回答

不使用readline函数,您可以通过regex读取整个内容和拆分行:

import re

with open("txt", "r") as f:
    content = f.read()
    # remove end line characters
    content = content.replace("\n", "")
    # split by lines
    lines = re.compile("(\[[0-9//, :\]]+)").split(content)
    # clean "" elements
    lines = [x for x in lines if x != ""]
# join by pairs
lines = [i + j for i, j in zip(lines[::2], lines[1::2])]

如果所有内容都有相同的开头[…],则可以按此分隔,然后清除所有忽略“”元素的部分。然后可以使用zip函数(https://stackoverflow.com/a/5851033/1038301)连接每个部分

Python 3允许您定义特定文件的换行符。很少使用它,因为默认的通用换行模式非常宽容:

When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller.

因此,这里应该明确指出只有'\r\n'是行尾:

f= open("f.txt",mode='r',encoding='utf8', newline='\r\n')

# use enumerate to show that second line is read as a whole
for i, line in enumerate(fd):   
    print(i, line)

相关问题 更多 >