天天看点

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,这样工作目录就是当前目录了

当然,理想中的情况应该是当前文件在哪个目录,工作目录就在哪个目录,可惜搞半天还不会,暂时这么用用吧。