将 \r 文本转换为 \n 以便 readlines() 按预期工作 [英] Convert \r text to \n so readlines() works as intended

查看:36
本文介绍了将 \r 文本转换为 \n 以便 readlines() 按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,您可以使用

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

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

每一行都由 \n 分隔,但如果一行的内容有 \r 则它不会被视为新行.我需要将所有 \r 转换为 \n 并获得正确的列表 lines.

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.

如果我在 lines 中执行 .split('\r') 我会得到列表中的列表.

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

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

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.

我应该如何实施?

推荐答案

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

这会使用 Python 的 通用换行支持\r 被视为行尾.

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

这篇关于将 \r 文本转换为 \n 以便 readlines() 按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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