如何在Python中从父目录打开文本文件?



我试图从Python的父目录打开一个文本文件。下面是树(简化):

+ Project:
- main.py
+ Source:
+ Documents:
- hello.txt
+ Modules:
- second.py

我正试图从second.py中读取hello.txt

下面是second.py中的问题行:

file = open('../Documents/hello.txt', 'r')

返回错误:FileNotFoundError: [Errno 2] No such file or directory: '../Documents/hello.txt'

相对路径是相对于工作目录的。如果您在Projects目录下运行代码,则路径需要相对于该目录,因此您需要open('./Source/Documents/hello.txt')

您可以使用绝对路径:

file = open('/home/user/Project/Source/Documents/hello.txt

将Project上游的目录名更改为您设置的目录名

或者如果second.py不移动,你可以使用相对路径:

file = open('../Documents/hello.txt')

的. .'会把你带到父目录,然后你可以从那里下拉到Documents目录。你也可以把"…"堆叠起来。例如,您可以使用以下命令访问main.py:

file = open('../../main.py')

最新更新