输入错误打开python文件进行读取

时间:2014-02-20 11:16:39

标签: python python-3.x

我遇到了一个试图打开文本文件以便在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

我不清楚我在哪里使用不正确的类型......我能否了解为何这不起作用?

提前谢谢。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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()

更清洁,您可以“控制”解码,并且不会以打开的文件句柄或错误的编码结束。