Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vsc给出了一个错误,但是python idle没有发送?_Python_Visual Studio Code - Fatal编程技术网

Vsc给出了一个错误,但是python idle没有发送?

Vsc给出了一个错误,但是python idle没有发送?,python,visual-studio-code,Python,Visual Studio Code,我编写了一个程序,当我在VisualStudio代码中运行它时,它会给出一个错误,但当我在Python空闲环境中运行它时,它不会给出错误。我已经设置了环境变量,但它仍然不起作用。那么你能告诉我怎么解决这个问题吗 当我导入一个文件和各种我想使用不同文件的地方时,也会发生这种情况 这是我的compiler.py文件 fileName=“file.txt” file=open(“file.txt”、“r+”) def文件(fname): 将open(fname)作为f: 对于枚举(f)中的i,l: 通

我编写了一个程序,当我在VisualStudio代码中运行它时,它会给出一个错误,但当我在Python空闲环境中运行它时,它不会给出错误。我已经设置了环境变量,但它仍然不起作用。那么你能告诉我怎么解决这个问题吗

当我导入一个文件和各种我想使用不同文件的地方时,也会发生这种情况

这是我的compiler.py文件

fileName=“file.txt”
file=open(“file.txt”、“r+”)
def文件(fname):
将open(fname)作为f:
对于枚举(f)中的i,l:
通过
返回i+1
对于范围内的循环(文件名)+1):
打印(循环)
这是我的file.txt

hallo
当我在VisualStudio代码中运行此命令时,会出现以下错误

PS C:\Users\Harry Kruger\Documents\code> & "C:/Program Files (x86)/Python37-32/python.exe" "c:/Users/Harry Kruger/Documents/code/quicks/compiler.py"
hallo
Traceback (most recent call last):
  File "c:/Users/Harry Kruger/Documents/code/quicks/compiler.py", line 4, in <module>
    file = open("file.txt", "r+")
FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'

我猜您在目录
“c:/Users/Harry Kruger/Documents/code/quicks
中空闲运行python。因此,您的代码将通过,因为在此目录中(可能?)还有
文件.txt

但是在VS代码中,您似乎在C:\Users\Harry Kruger\Documents\Code目录下运行python,其中文件.txt不存在,因此代码失败。
要修复此问题并在VS代码中运行代码,您有两个选项:

  • 在VS Code powershell中,导航到包含文件.txt的目录。在您的情况下,您应该可以通过输入cd“c:/Users/Harry Kruger/Documents/Code/quicks”来执行此操作,然后调用您的代码
  • 您可以修改代码以使用文件的绝对路径。然后您可以从任何目录调用它。为此,您必须用open()修改
    语句。将其替换为:
    从操作系统导入路径
    将open(path.join(path.abspath(path.dirname(_文件__)),'file.txt'),'r+')作为f:
    
    此snipet将查找文件的绝对路径并将其打开

  • 如果你不了解我的程序,请问我我不是最好的程序员。
    file.txt
    在哪里?你检查了cwd(当前工作目录)了吗在VSCode?下运行代码时,根据代码中的路径名,
    file.txt
    应与compiler.py位于同一目录中。@Shiva-hmm我不确定你的意思,但它与compiler.py位于同一文件夹中。你的选项1很简单,但选项2是希腊语,所以我只做1
    0
    1