如何在Windows中强制Python的file.write()在Windows中使用与Linux中相同的换行格式("\ r \ n"与"\ n")? [英] How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?

查看:500
本文介绍了如何在Windows中强制Python的file.write()在Windows中使用与Linux中相同的换行格式("\ r \ n"与"\ n")?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的代码:

f = open('out.txt','w')
f.write('line1\n')
f.write('line2')
f.close()

代码在Windows上运行并给出文件大小12 bytes,而Linux给出11 bytes 原因是换行

Code runs on windows and gives file size 12 bytes, and linux gives 11 bytes The reason is new line

在Linux中,它是\n,对于胜利而言,它是\r\n

In linux it's \n and for win it is \r\n

但是在我的代码中,我将新行指定为\n.问题是如何使python始终保持换行为\n,而不检查操作系统.

But in my code I specify new line as \n. The question is how can I make python keep new line as \n always, and not check the operating system.

推荐答案

您需要以 binary模式打开文件,即wb而不是w.如果不这样做,则行尾字符会自动转换为特定于OS的字符.

You need to open the file in binary mode i.e. wb instead of w. If you don't, the end of line characters are auto-converted to OS specific ones.

以下是Python参考资料的摘录,内容涉及 open() .

Here is an excerpt from Python reference about open().

默认设置是使用文本模式,该模式可以在书写时将'\ n'字符转换为特定于平台的表示形式,在读取时又可以转换为该形式.

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.

这篇关于如何在Windows中强制Python的file.write()在Windows中使用与Linux中相同的换行格式("\ r \ n"与"\ n")?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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