2014-09-29 21 views

回答

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

你可以創建自己的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) 
+0

我不會說這個簡單的方法,但它是一個有趣的方法,tnx – Bob 2014-10-08 23:58:30

1

如果確定有一個名爲open你上面提到的方法,然後定義這樣的功能

import functools  
open_file = functools.partial(open, encoding='utf-8') 

然後,開用這種新方法文件,

f = open_file('some_file.txt', 'r') 
相關問題