[英]Elegant way to handle Python file read option rU in both py2 and py3
在 Python 2 和 3 中以優雅的方式使用讀取模式“rU”(讀取具有通用換行支持的文件)讀取文件的最佳方法是什么? Py3.4 最近棄用了這個,導致 DeprecationWarings:
with open(filename, 'rU') as handle:
content = handle.read()
我沒有看到一種方法來調用open()
並巧妙地混合參數以使其對兩者都有效。 我將它包裝在一個區分 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.