将 \r 文本转换为 \n 以便 readlines() 按预期工作

发布于 2024-08-12 08:15:28 字数 457 浏览 2 评论 0原文

在 Python 中,您可以读取文件并将其行加载到列表中,方法是使用

f = open('file.txt','r')
lines = f.readlines()

每个单独的行由 \n 分隔,但如果行的内容有 \r 那么它不被视为新行。我需要将所有 \r 转换为 \n 并获取正确的列表 lines

如果我在 lines 内执行 .split('\r') 我将在列表中获得列表。

我想过打开一个文件,将所有 \r 替换为 \n,关闭文件并再次读取它,然后使用 readlines() 但这似乎很浪费。

我应该如何实施这个?

In Python, you can read a file and load its lines into a list by using

f = open('file.txt','r')
lines = f.readlines()

Each individual line is delimited by \n but if the contents of a line have \r then it is not treated as a new line. I need to convert all \r to \n and get the correct list lines.

If I do .split('\r') inside the lines I'll get lists inside the list.

I thought about opening a file, replace all \r to \n, closing the file and reading it in again and then use the readlines() but this seems wasteful.

How should I implement this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

云柯 2024-08-19 08:15:28
f = open('file.txt','rU')

这将使用 Python 的 通用换行符支持\r 被视为行尾。

f = open('file.txt','rU')

This opens the file with Python's universal newline support and \r is treated as an end-of-line.

涙—继续流 2024-08-19 08:15:28

如果有问题,请以二进制格式打开并使用以下代码进行转换:

from __future__ import with_statement

with open(filename, "rb") as f:
    s = f.read().replace('\r\n', '\n').replace('\r', '\n')
    lines = s.split('\n')

If it's a concern, open in binary format and convert with this code:

from __future__ import with_statement

with open(filename, "rb") as f:
    s = f.read().replace('\r\n', '\n').replace('\r', '\n')
    lines = s.split('\n')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文