chi*_*gsy 13 python bash file line-endings line-breaks
我有一堆文件.有些是Unix行结尾,很多都是DOS.在切换行结尾之前,我想测试每个文件以查看是否格式化dos.
我该怎么做?有没有我可以测试的旗帜?相似的东西?
Eri*_*got 29
由于"通用换行模式"(),Python可以自动检测文件中使用的换行约定U,并且可以通过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)
Run Code Online (Sandbox Code Playgroud)
这给出了第一行的换行符(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
Run Code Online (Sandbox Code Playgroud)