简体   繁体   中英

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? Py3.4 has recently deprecated this, causing 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. I'd wrap it in a helper method which distinguishes between Python 2 and 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM