[英]Finding absolute file path
我一直在研究這個 Python 項目,剛剛意識到存在一個問題。 起初我以為它只是在 Linux 中,因為我試圖創建一個命令來打開文件路徑中的文件,然后意識到當它在目標文件夾之外的任何時間運行時,即使在 Windows 中它也會運行錯誤。 所以它必須是我的代碼的一般問題。 基本上我試圖調用程序從文本文件中讀取和打印數據。
help_text = open("files/help_text.txt","r")
help_text_content = help_text.read()
print(help_text_content)
我想要做的就是確保無論.py
文件位於何處,它都能讀取文件。 我不能做C:\\Location
因為如果用戶安裝文件它可能位於其他地方。 所以我需要一個知道文件本身在哪里的絕對位置讀取器。
在 Python 中處理文件路徑的最佳方法是使用pathlib 。 這確保處理使用正確的路徑分隔符等的所有細節。 我會使用這樣的代碼:
import pathlib
# path of the current script:
parent = pathlib.Path(__file__).parent
help_file = parent / 'files' / 'help_text.txt'
# note: you can check that this file exists
if not help_file.is_file():
raise FileNotFoundError('Help file not found')
with help_file.open() as f:
help_text_content = f.read()
print(help_text_content)
我想可能使用os
模塊可以幫助您獲取當前工作目錄文件,然后您可以附加help_text.txt
以獲取位置:
import os
current_dir = os.getcwd()
# /C:/User/
path= os.path.join(current_dir, "help_text.txt")
# /C:/User/help_text.txt
根據注釋中提供的信息(txt 文件始終位於 files/ 中,它始終與 .py 文件配對)-您需要獲取 py 文件的位置。 請注意,它可能(並且在出現此錯誤的情況下顯然是)與您執行 py 腳本的當前工作目錄不同。 有關擴展討論,請參閱如何獲取當前正在執行的文件的路徑和名稱?
然后你需要將 py 文件的路徑和"files/help_text.txt"
。 當然,您可以使用標准庫中的os
模塊或(更好的) pathlib
模塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.