繁体   English   中英

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

[英]How do I open a text file from a parent directory in 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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM