python:“TypeError:打开文件时应为str、bytes或os.PathLike对象,而不是list”

2024-05-18 10:53:09 发布

您现在位置: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

Tags: docmydirwithhelpopenfilenamemyfile
1条回答
网友
1楼 · 发布于 2024-05-18 10:53:09

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

docs开始:

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

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)


可以使用字符串作为open函数的参数:

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

相关问题 更多 >