如何使用Python在Windows中编写Unix行尾字符 [英] How to write Unix end of line characters in Windows using Python

查看:103
本文介绍了如何使用Python在Windows中编写Unix行尾字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Python(在Windows上)写入文件并使用Unix行尾字符?

How can I write to files using Python (on Windows) and use the Unix end of line character?

例如做的时候:


f = open('file.txt', 'w')
f.write('hello\n')
f.close()

Python会自动将\ n替换为\ r \ n.

Python automatically replaces \n with \r\n.

推荐答案

对于Python 2& 3

请参阅:现代的方式:在此页面上使用newline =''答案.

以二进制格式打开文件以防止行尾字符的翻译:

Open the file as binary to prevent the translation of end-of-line characters:

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

引用Python手册:

Quoting the Python manual:

在Windows上,附加到该模式的'b'以二进制模式打开文件,因此也有诸如'rb','wb'和'r + b'之类的模式. Windows上的Python区分文本文件和二进制文件.读取或写入数据时,文本文件中的行尾字符会自动更改.对文件数据进行这种幕后修改对ASCII文本文件来说是很好的选择,但它会破坏二进制数据,如JPEG或EXE文件中的那样.读写此类文件时,请务必小心使用二进制模式.在Unix上,将'b'附加到该模式并没有什么坏处,因此您可以在所有二进制文件中独立使用它.

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

这篇关于如何使用Python在Windows中编写Unix行尾字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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