2014-02-20 69 views
0

我遇到一個問題試圖打開一個文本文件,用於在Python 3.閱讀的代碼如下:類型錯誤打開Python文件讀取

def main(): 
the_file = input('What is the name of the file?') 

open_file = open(the_file,"r","utf8") 
open_file.read() 

,然後我打電話的功能。

,我得到的錯誤是:

Traceback (most recent call last): 
    File "/Users/Matthew/Desktop/CaesarCipher.py", line 9, in <module> 
    main() 
    File "/Users/Matthew/Desktop/CaesarCipher.py", line 7, in main 
    open_file = open(encrypted_file,"r","utf8") 
TypeError: an integer is required 

這我不清楚,我現在用了不正確的類型......我能得到一些見解,爲什麼這是不工作?

預先感謝您。

回答

1

這解決了這個問題:

open_file = open(the_file,"r") 

第三參數是一個buffer parameter,而不是編碼?

所以,你可以做的是:

open_file = open(the_file,"r", 1, 'utf-8') # 1 == line Buffered reading 

還..
你應該這樣做,而不是:

with open(the_file, 'rb') as fh: 
    data = fh.read().decode('utf-8') 

with open(the_file, 'r', -1, 'utf-8') as fh: 
    data = fh.read() 

清潔,你會得到「控制「在解碼之後,不會以打開的文件句柄或錯誤的編碼結束。

+0

'打開()'在Python 2和Python 3功能有不同的參數例如,Python 2中的'open()'funciton沒有'encoding'參數。不要鏈接到Python 2文檔的Python 3問題。 – jfs

+0

'buffering = 1'表示*行*緩衝(它不僅意味着緩衝被啓用,例如,默認的'buffering = -1'意味着緩衝區大小等於'io.DEFAULT_BUFFER_SIZE')。 – jfs

+0

以文本模式「r''打開的文件會生成Unicode字符串。在它們上面調用'.decode('utf-8')是不正確的(在Python 3中''str'對象沒有屬性'decode') – jfs

2

的第三參數open()buffering

open(file, mode='r', buffering=-1, encoding=None, 
    errors=None, newline=None, closefd=True, opener=None) -> file object 

傳遞的字符編碼作爲代替關鍵字參數:

with open(the_file, encoding="utf-8") as file: 
    text = file.read()