我正在尝试访问Python中的.txt文件,我无法弄清楚如何打开文件.我最终直接将内容复制到列表中,但我想知道如何打开未来的文件.
如果我跑这个没什么打印.我认为这是因为Python正在查找错误的文件夹/目录,但我不知道如何更改文件路径.
sourcefile = open("CompletedDirectory.txt").read()
print(sourcefile)
Run Code Online (Sandbox Code Playgroud)
该文件CompletedDirectory.txt可能是空的.
如果Python找不到该文件,您将收到FileNotFoundError异常:
>>> sourcefile = open("CompletedDirectory.txt").read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'CompletedDirectory.txt'
Run Code Online (Sandbox Code Playgroud)
请注意,read()不建议以这种方式使用.你没有正确关闭文件.使用上下文管理器:
with open("CompletedDirectory.txt") as infile:
sourcefile = infile.read()
Run Code Online (Sandbox Code Playgroud)
这将infile在离开with块时自动关闭.