有一個簡單和跨平臺的方式來設置默認編碼在Python打開文件(文本模式),這樣你就不必每次都寫Python簡單的方法來設置在文本模式下打開文件的默認編碼?
open(filename, 'r', encoding='utf-8')
,並可以簡單的寫
open(filename, 'r')
?
有一個簡單和跨平臺的方式來設置默認編碼在Python打開文件(文本模式),這樣你就不必每次都寫Python簡單的方法來設置在文本模式下打開文件的默認編碼?
open(filename, 'r', encoding='utf-8')
,並可以簡單的寫
open(filename, 'r')
?
from io import open # for python2 compatibility
old_open = open
def open(*args, **kwargs):
encoding = kwargs.pop('encoding', 'utf8')
return old_open(*args, encoding=encoding, **kwargs)
你可以創建自己的contextmanager:
import contextlib
@contextlib.contextmanager
def start_transaction(f ,mode="r", enc="utf-8"):
f = open(f, mode, encoding=enc)
try:
yield f
except:
raise
with start_transaction("in.txt") as f:
for line in f:
print (line)
我不會說這個簡單的方法,但它是一個有趣的方法,tnx – Bob 2014-10-08 23:58:30
如果確定有一個名爲open
你上面提到的方法,然後定義這樣的功能
import functools
open_file = functools.partial(open, encoding='utf-8')
然後,開用這種新方法文件,
f = open_file('some_file.txt', 'r')
定義你自己的'open'功能?例如'def myopen(* args):return open(* args,encoding ='utf-8')' – isedev 2014-09-29 23:36:18