Stack Overflow 上也存在類似的問題。我已經閱讀了這些問題,但它們并沒有解決我的問題。下面的簡單代碼導致檔案未找到錯誤。我在 Mac OS X 11.4 上運行 Python 3.9.1
任何人都可以建議下一步解決此問題的原因嗎?
with open("/Users/root/test/test.txt", "w ") as f:
f.write("test")
Traceback (most recent call last):
File "/Users/root1/PycharmProjects/web_crawler/test.py", line 1, in <module>
with open("/Users/root/test/test.txt", "w ") as f:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/root/test/test.txt'
uj5u.com熱心網友回復:
您對初始帖子的評論闡明了您需要發生的事情。
下面假設
- 目錄
Users/root1/存在 - 您正在嘗試在其中創建一個新的子目錄 檔案
import os
# Wrap this in a loop if you need
new_dir = 'test' # The variable directory name
new_path = 'Users/root1/' new_dir "/"
os.makedirs(os.path.dirname(new_path), exist_ok=True) # Create new dir 'Users/root1/${new_dir}/
with open(new_path "test.txt", "w ") as f:
# Create new file in afore created directory
f.write("test")
這將根據變數創建一個新目錄new_dir并test.txt在其中創建檔案。
uj5u.com熱心網友回復:
**有時編譯器找不到您在 open() 函式中插入的任何路徑。那時你可以默認保存在IDE保存程式的檔案夾中。以下語法可能對您有所幫助**
with open('test.txt', 'w ') as f:
f.write("xyz")
**這里的 text.txt 將默認保存在您的 IDE 存盤您撰寫的程式的檔案夾中。您可以檢查該檔案夾的構造**
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/359024.html
