VS代码- Python代码无法正确打开文件[重复]

o4tp2gmn  于 5个月前  发布在  Python
关注(0)|答案(2)|浏览(83)

此问题在此处已有答案

Python script can't find file when opening with VS code, but works OK with terminal(2个答案)
17小时前关闭
我写了这段代码来使用VS CODE在python中打开一个文件-

with open("Answer Words.txt") as Answer_Words_File:
    Answer_Words = Answer_Words_File.read()

字符串
但是它说“FileNotFoundError:[Errno 2] No such file or directory:'Answer Words.txt'“当我以前使用PyCharm时,这段代码可以工作,因为文本文件和我的python项目在同一个文件夹中。
我还尝试使用文件路径或写入-Answer_Words = open("Answer Words.txt", "r")
没有任何工作
我需要使用图书馆吗?

uinbv5nw

uinbv5nw1#

我希望你的终端是不是在正确的路径,如果文件没有打开。以确保您的文件是在您执行此代码的路径可用。您可以使用下面提到的代码

import os
current_directory = os.getcwd()
files_in_directory = os.listdir(current_directory)

# Print the list of files
print("Files in the current directory:")
for file in files_in_directory:
    print(file)

字符串

vh0rcniy

vh0rcniy2#

我的VS代码默认文件夹在C:\User\user中。如果你保存“Answer Words.txt”在默认文件夹中,它应该能正常运行。或者你可以将终端设置为你的操作文件夹,它也能正常运行。

相关问题