天天看點

VSCode中python報錯No such file or directory

目前目錄為

D:\work\python\filetest

,目錄下放有py檔案和要讀取的檔案

VSCode中python報錯No such file or directory

test.py

内容如下

with open('1.txt') as file_name:
    name = file_name.read()
print(name)
           

但運作後會報錯

FileNotFoundError: [Errno 2] No such file or directory: '1.txt'
           

這怎麼回事,明明

1.txt

在同一目錄啊,并且指令行直接運作也沒問題

VSCode中python報錯No such file or directory

排查後發現為vscode的問題

我vscode的工作目錄一直都是work,但檔案是放在

\work\python\filetes

目錄下的

VSCode中python報錯No such file or directory

解決辦法:

讀取的檔案路徑寫全

python\\filetest\\1.txt

,或者寫絕對路徑

D:\\work\\python\\filetest\\1.txt

或者cd到目前目錄

VSCode中python報錯No such file or directory

或者右鍵檔案夾打開vscode,這樣工作目錄就是目前目錄了

當然,理想中的情況應該是目前檔案在哪個目錄,工作目錄就在哪個目錄,可惜搞半天還不會,暫時這麼用用吧。