簡體   English   中英

鍵入錯誤打開python文件進行讀取

[英]Type Error opening python file for reading

我試圖打開一個文本文件以在Python 3中閱讀時遇到問題。代碼如下:

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

我不清楚我在哪里使用了不正確的類型...我可以了解為什么它不起作用嗎?

先感謝您。

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

這解決了問題:

open_file = open(the_file,"r")

第三個參數是緩沖區參數 ,而不是編碼?

因此,您可以做的是:

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

更干凈的是,您可以控制解碼,並且不會以打開的文件句柄或錯誤的編碼結尾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM