[英]Elegant way to handle Python file read option rU in both py2 and py3
What is the best way to read a file using the read mode 'rU' (read a file with universal newline support) in an elegant way in Python 2 and 3?在 Python 2 和 3 中以优雅的方式使用读取模式“rU”(读取具有通用换行支持的文件)读取文件的最佳方法是什么? Py3.4 has recently deprecated this, causing DeprecationWarings:
Py3.4 最近弃用了这个,导致 DeprecationWarings:
with open(filename, 'rU') as handle:
content = handle.read()
I don't see a way to call open()
with a clever mix of arguments to make it work for both.我没有看到一种方法来调用
open()
并巧妙地混合参数以使其对两者都有效。 I'd wrap it in a helper method which distinguishes between Python 2 and 3:我将它包装在一个区分 Python 2 和 3 的辅助方法中:
import sys
if sys.version_info[0] == 2:
def open_text(filename):
return open(filename, 'rU')
else:
def open_text(filename):
return open(filename, 'r', newline=None)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.