Skip to main content
 首页 » 编程设计

python之在 py2 和 py3 中处理 Python 文件读取选项 rU 的优雅方式

2024年10月25日17haluo1

在 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)