如何使用Python(在Windows上)写入文件并使用Unix行尾字符?
例如,当做:
f = open('file.txt', 'w')
f.write('hello\n')
f.close()
Python自动用\ r \n替换\n.
我想使用在Linux上运行的python编写带有DOS/Windows行结尾'\ r \n'的文本文件.在我看来,必须有比手动放一个"\ r \n"在每行的末尾或者使用终止转换工具行更好的办法.理想情况下,我希望能够执行一些操作,例如将os.linesep分配给我在编写文件时要使用的分隔符.或者在我打开文件时指定行分隔符.
如果考虑到carriage return = \r和line feed = \n
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> '{:02x}'.format(ord('\n'))
'0a'
>>> '{:02x}'.format(ord('\r'))
'0d'
Run Code Online (Sandbox Code Playgroud)
使用时如何避免写回车open('filename','w').write('text\n')?
在交互模式下,您可以这样做:
>>> open('filename','w').write('text\n')
5
>>> for c in open('filename','r').read():
... print('{:02x}'.format(ord(c)))
...
74
65
78
74
0a
Run Code Online (Sandbox Code Playgroud)
这表示只写入换行符,因此它应该是5个字节长.
-rw-r--r-- 1 djuric 197121 6 Jul 15 21:00 filename
^
Run Code Online (Sandbox Code Playgroud)
它实际上是6个字节长.现在这可以是"Windows的东西",但是当您在Notepad ++中打开文件时,如果您打开视图>显示符号>显示所有字符,您可以看到回车符.
按CTRL + H并使用扩展搜索模式替换\ r时,只剩下换行符.保存文件后,只有换行符在文件中,文件长度为5个字节.
-rw-r--r-- 1 …Run Code Online (Sandbox Code Playgroud) 我需要将一些文本写入文件,同时包含换行符 \r 和 \n 的混合,我想同时保留两者。但是,在 python 3 中,当我将此文本写入文件时,\r 的所有实例都替换为 \n。这种行为与 python 2 不同,你可以在下面的输出中看到。我能做些什么来阻止这种更换?
这是代码:
import string
printable=string.printable
print([printable])
fopen=open("test.txt","w")
fopen.write(printable)
fopen.close()
fopen=open("test.txt","r")
content=fopen.read()
print([content])
fopen.close()
Run Code Online (Sandbox Code Playgroud)
这是输出,当我在 python 2 和 python 3 上运行代码时:
(base) Husseins-Air:Documents hmghaly$ python2.7 test_write_line_break.py
['0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c']
['0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c']
(base) Husseins-Air:Documents hmghaly$ python test_write_line_break.py
['0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c']
['0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\n\x0b\x0c']
Run Code Online (Sandbox Code Playgroud)