[英]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.