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

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

问题描述

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

例如做的时候:

<前>f = open('file.txt', 'w')f.write('你好\n')f.close()

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

解决方案

For Python 2 &3

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

仅适用于 Python 2(原始答案)

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

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

引用 Python 手册:

<块引用>

在 Windows 上,附加到模式的 'b' 以二进制模式打开文件,因此也有像 'rb'、'wb' 和 'r+b' 这样的模式.Windows 上的 Python 区分文本文件和二进制文件;读取或写入数据时,文本文件中的行尾字符会自动稍微改变.这种对文件数据的幕后修改适用于 ASCII 文本文件,但它会破坏 JPEG 或 EXE 文件中的二进制数据.读写此类文件时要非常小心地使用二进制模式.在 Unix 上,将 'b' 附加到模式并没有什么坏处,因此您可以独立于平台对所有二进制文件使用它.

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

e.g. When doing:

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

Python automatically replaces \n with \r\n.

解决方案

For Python 2 & 3

See: The modern way: use newline='' answer on this very page.

For Python 2 only (original answer)

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

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

Quoting the Python manual:

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.

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

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