在Mac vs Windows上的python中处理\ r \ n vs \ n换行符 [英] Handling \r\n vs \n newlines in python on Mac vs Windows

查看:129
本文介绍了在Mac vs Windows上的python中处理\ r \ n vs \ n换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python脚本,当在Windows机器上运行和在Mac上运行时,它们给出不同的输出.在深入研究时,我发现这是因为当Python在Mac上从文件中读取换行符(从文件中)时,它在\r\n中读取,而在Windows中,\r则以某种方式消失了.

I have a python script that gave different output when run on a Windows machine and when run on a Mac. On digging deeper, I discovered that it was because when Python read in line breaks on the Mac (from a file), it read in \r\n, while somehow in Windows the \r disappears.

因此,如果我将脚本中的每个\n都更改为\r\n,则在Mac上可以正常使用.但是,如果这样做,它将在Windows PC上停止工作.

Thus, if I change every \n in the script to \r\n, it works fine on the Mac. But if I do that, it stops working on the Windows PC.

有解决此问题的简便方法吗?

Is there an easy way to fix this problem?

推荐答案

我想这可能取决于您从中读取的内容,但是内置的open()函数采用"mode"参数,如果您通过对于"U"模式,Python将以跨平台的方式透明地处理换行符.它要求Python具有通用的换行符支持,但请对其进行测试!

I guess it may depend on what you're reading from, but the built-in open() function takes a 'mode' parameter, and if you pass 'U' for the mode, Python will take care of the newlines in a cross-platform way transparently. It requires that Python be built with universal newline support, but test it out!

http://docs.python.org/library/functions.html#open

这篇关于在Mac vs Windows上的python中处理\ r \ n vs \ n换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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