\parentDirectory
\subdr1
-testfile.txt
\subdr2
\childdir
-file.json
-file2.pickle
-fileOpener.py
我想使用 Python 從 fileOpener.py 讀取 file.json:
with open("./childdir/file.json", 'r') as f:
但我收到 FileNotFoundError。
FileNotFoundError: [Errno 2] No such file or directory: './childdir/file.json'
有人介意解決這個問題嗎?我正在使用 WINDOWS 作業系統。
uj5u.com熱心網友回復:
如果你在fileOpener.py范圍內運行,subdir2那么一切都很好。當你不在時,問題就會發生subdir2。這是解決方案:
import pathlib
this_script = pathlib.Path(__file__)
json_path = this_script.parent / "childdir" / "file.json"
with open(json_path, 'r') as f:
...
由于pathlib是跨平臺的,因此這段代碼應該可以在 Windows 下運行。我在 Mac 和 linux 下測驗過。
uj5u.com熱心網友回復:
首先,您使用的是哪個作業系統?因為 Windows 使用\和基于 UNIX 的作業系統使用/
最好的方法是使用 os 模塊中的路徑,如下所示:
import os
with open(os.path.join('childdir', 'file.json'), 'r')" as f:
# YOUR CODE
這是一種更好的方法,因為它獨立于平臺,因為它會根據您所在的作業系統適當地創建路徑。
uj5u.com熱心網友回復:
這是因為您要打開的檔案位于當前作業目錄的子目錄中(python 檔案所在的位置)。你需要在這里考慮兩件事,
取決于您使用的作業系統,它是基于 UNIX 的 '/' 和基于 Windows 的 '' 作為檔案路徑中的分隔符
我們可以使用檔案的絕對路徑和模式打開檔案,也可以使用該 os 模塊的路徑子模塊。
# With absolute path in Windows
with open('F:\parentDirectory\subdr2\childdir\file.json', mode(r/a/w..)) as fl:
# logic
或者
# with os.path submodule
import os
with open(os.path.join('childdir', 'file.json'), mode('r/w/a/..')) as fl:
# logic
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/505071.html
標籤:Python json 文件 机器学习 视觉工作室代码
下一篇:Python:如何獲取str串列中的每個元素,然后將第一個元素放入目錄中的第一個檔案,第二個目錄中的第二個元素?
