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

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

问题描述

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

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 , while somehow in Windows the disappears.

因此,如果我将脚本中的每个 更改为 ,它在 Mac 上运行良好.但如果我这样做,它就无法在 Windows PC 上运行了.

Thus, if I change every in the script to , 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?

推荐答案

'U' 模式:

Python 2:

我想这可能取决于您正在阅读的内容,但是内置的 open() 函数需要一个模式"参数,如果您为模式传递U",Python 2 将处理透明地以跨平台方式换行.它要求 Python 构建时支持通用换行符,但请测试一下!

'U' mode:

Python 2:

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 2 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!

https://docs.python.org/2/library/functions.html#open

在 Python 3 中,'U' 模式是默认行为,如文档所述:

In Python 3, the 'U' mode is the default behaviour, as the docs explain:

允许使用额外的模式字符 'U',它不再有任何效果,被视为已弃用.它之前在文本模式下启用了通用换行符,这成为Python 3.0 中的默认行为.请参阅 newline 参数的文档以获取更多信息详情.

There is an additional mode character permitted, 'U', which no longer has any effect, and is considered deprecated. It previously enabled universal newlines in text mode, which became the default behaviour in Python 3.0. Refer to the documentation of the newline parameter for further details.

https://docs.python.org/3/library/functions.html#open

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

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