如何检测文件中的DOS换行符?

问题描述 投票:12回答:7

我有一堆文件。有些是Unix行结尾,很多都是DOS。在切换行结尾之前,我想测试每个文件以查看是否格式化dos。

我该怎么做?有没有我可以测试的旗帜?相似的东西?

python bash file line-breaks line-endings
7个回答
8
投票

你可以在字符串中搜索\r\n。这是DOS风格的结尾。

编辑:看看this


28
投票

由于“通用换行模式”(U),Python可以自动检测文件中使用的换行约定,并且可以通过文件对象的newlines属性访问Python的猜测:

f = open('myfile.txt', 'U')
f.readline()  # Reads a line
# The following now contains the newline ending of the first line:
# It can be "\r\n" (Windows), "\n" (Unix), "\r" (Mac OS pre-OS X).
# If no newline is found, it contains None.
print repr(f.newlines)

这给出了第一行的换行符(Unix,DOS等),如果有的话。

正如John M.指出的那样,如果你有一个使用多个换行符编码的病态文件,f.newlines是一个元组,在阅读了很多行之后,到目前为止找到了所有新行编码。

参考:http://docs.python.org/2/library/functions.html#open

如果您只想转换文件,只需执行以下操作:

with open('myfile.txt', 'U') as infile:
    text = infile.read()  # Automatic ("Universal read") conversion of newlines to "\n"
with open('myfile.txt', 'w') as outfile:
    outfile.write(text)  # Writes newlines for the platform running the program

3
投票

(仅限Python 2 :)如果您只想读取DOS或Unix格式的文本文件,则可以:

print open('myfile.txt', 'U').read()

也就是说,Python的“通用”文件阅读器将自动使用所有不同的行标记,将它们翻译为“\ n”。

http://docs.python.org/library/functions.html#open

(谢谢句柄!)


1
投票

作为一个完整的Python新手,只是为了好玩,我试图找到一种简单的方法来检查一个文件。这似乎有效:

if "\r\n" in open("/path/file.txt","rb").read():
    print "DOS line endings found"

编辑:根据John Machin的评论进行简化(无需使用正则表达式)。


0
投票

dos换行符是qazxsw poi,unix只有qazxsw poi。所以只需搜索\r\n


0
投票

使用grep&bash:

\n

0
投票

您可以使用以下函数(应该在Python 2和Python 3中工作)来获取现有文本文件中使用的换行符表示形式。所有三种可能的类型都被认可。该函数只读取文件直到第一个换行符来决定。当您有较大的文本文件时,这会更快,更少占用内存,但它不会检测混合的换行结尾。

在Python 3中,您可以在写入文件时将此函数的输出传递给\r\n函数的grep -c -m 1 $'\r$' file echo $'\r\n\r\n' | grep -c $'\r$' # test echo $'\r\n\r\n' | grep -c -m 1 $'\r$' 参数。这样,您可以在不更改其换行符表示的情况下更改文本文件的上下文。

newline
© www.soinside.com 2019 - 2024. All rights reserved.