使用Python 3.9,我想“输入”文件路径(通过输入函数)。然后我想打开该文件路径。我受到以下错误的阻碍:
OSError: [Errno 22] Invalid argument: "'C:\\\\Users\\\\Hart\\\\Documents\\\\File.txt'"
我想知道为什么。
这是我所知道的:我有一个文件路径。根据os.path.exists,文件路径存在。
>>> os.path.exists("C:\\Users\\Hart\\Documents\\File.txt")
True
我可以打开文件。
>>> open("C:\\Users\\Hart\\Documents\\File.txt")
<_io.TextIOWrapper name='C:\\Users\\Hart\\Documents\\File.txt' mode='r' encoding='cp1252'>
我可以将该文件命名为任何名称,但它仍然存在,并且我仍然可以打开它。
>>> anything = "C:\\Users\\Hart\\Documents\\File.txt"
>>> os.path.exists(anything)
True
>>> open(anything)
<_io.TextIOWrapper name='C:\\Users\\Hart\\Documents\\File.txt' mode='r' encoding='cp1252'>
但我想通过输入函数间接打开文件。
>>> file = input('Enter a file path\n')
Enter a file path
'C:\\Users\\Hart\\Documents\\File.txt'
这将创建一个名为 file 的变量,它类似于我的文件路径。
>>> print(file)
'C:\\Users\\Hart\\Documents\\File.txt'
但当我尝试打开它时...
OSError: [Errno 22] Invalid argument: "'C:\\\\Users\\\\Hart\\\\Documents\\\\File.txt'"
该变量表示的文件也不存在。
>>> os.path.exists(file)
False
这是怎么回事?