gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:21:41 24 4
gpt4 key购买 nike

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

我该怎么做?有我可以测试的标志吗?类似的东西?

最佳答案

Python 可以自动检测文件中使用的换行约定,这要归功于“通用换行模式”(U),您可以通过文件对象的 newlines 属性:

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

关于python - 如何检测文件中的 DOS 换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2798627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com