python:打开文件时,“ TypeError:预期的str,字节或os.PathLike对象,而不是列表”

时间:2020-04-18 11:55:46

标签: python

我尝试读取输入文件。

Myfile = list(input("Please enter a filename with full dir: "))
fp = open(Myfile)
sstr = fp.read()

但总是显示错误:

"D:\Program Files\Python\python.exe" D:/Onebox/Python/my_help_doc/guo.py
Please enter a filename with full dir: 'E:\个人\郭周诺\Python\guo-python.txt'
Traceback (most recent call last):
  File "D:/Onebox/Python/my_help_doc/guo.py", line 7, in <module>
    fp = open(Myfile)
TypeError: expected str, bytes or os.PathLike object, not list

Process finished with exit code 1

1 个答案:

答案 0 :(得分:1)

对于open内置函数,您应该有一个类似路径的对象而不是列表作为参数

来自docs

打开(文件,模式=“ r”,缓冲= -1,编码=无,错误=无, newline = None,closefd = True,opener = None)

打开文件并返回一个 相应的文件对象。如果无法打开文件,则出现OSError。 提出。

file is a path-like object给出路径名(绝对或相对) 到当前工作目录)或要打开的文件 要包装的文件的整数文件描述符。 (如果有文件 给定描述符,当返回的I / O对象为 关闭,除非closefd设置为False。)


您可以将字符串用作open函数的参数:

my_file = input("Please enter a filename with full dir: ")
fp = open(my_file)