[英]How do I change/choose the file path in Python?
I'm trying to access a .txt file in Python and I can't figure out how to open the file. 我正在尝试使用Python访问.txt文件,但我不知道如何打开该文件。 I ended up copying the contents into a list directly but I would like to know how to open a file for the future.
我最终将内容直接复制到列表中,但是我想知道将来如何打开文件。
If I run this nothing prints. 如果运行此命令,则不会打印任何内容。 I think it's because Python is looking in the wrong folder/directory but I don't know how to change file paths.
我认为这是因为Python在错误的文件夹/目录中查找,但我不知道如何更改文件路径。
sourcefile = open("CompletedDirectory.txt").read()
print(sourcefile)
The file CompletedDirectory.txt
is probably empty. 文件
CompletedDirectory.txt
可能为空。
If Python could not find the file, you would get a FileNotFoundError
exception: 如果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'
Note that using read()
in this way is not recommended. 请注意,不建议以这种方式使用
read()
。 You're not closing the file properly. 您没有正确关闭文件。 Use a context manager:
使用上下文管理器:
with open("CompletedDirectory.txt") as infile:
sourcefile = infile.read()
This will automatically close infile
on leaving the with
block. 这将自动关闭
infile
在离开with
块。
You can get the current working directory: 您可以获取当前的工作目录:
import os
os.getcwd()
Then just concat it with the file container directory 然后将其与文件容器目录连接
os.path.join("targetDir", "fileName")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.