简体   繁体   English

无法使用 VS Code 在 python 中打开文件

[英]Trouble opening files in python with VS Code

I can't seem to open basic text files when I run a python script in VS Code, the code runs fine when I use it in Idle but VSCode will give me a FileNotFound error, is there some sort of extension that allows me to do this?当我在 VS Code 中运行 python 脚本时,我似乎无法打开基本文本文件,当我在 Idle 中使用它时代码运行良好,但 VSCode 会给我一个 FileNotFound 错误,是否有某种扩展允许我做这个? Right now I'm only using the Python and Code Runner extension.现在我只使用 Python 和 Code Runner 扩展。 example of my code:我的代码示例:

def getInput(textFile):
    file=open(textFile,'r')
    print(file.readlines())

Try setting尝试设置

"python.terminal.executeInFileDir": true, “python.terminal.executeInFileDir”:真,

in your VSCode Settings在你的 VSCode 设置中

In your VSCode for Windows在你的 VSCode for Windows 中

File --> Preferences --> Settings --> (User)Extensions --> Python -->文件 --> 首选项 --> 设置 -->(用户)扩展 --> Python -->

Terminal: Execute In File Dir --> Check It终端:在文件目录中执行--> 检查

or

File --> Preferences --> Settings --> Search Settings --> python.terminal.executeInFileDir文件 --> 首选项 --> 设置 --> 搜索设置 --> python.terminal.executeInFileDir

I don't know what is wrong with your vscode setup but you can improve your code. 我不知道您的vscode设置有什么问题,但是您可以改善代码。

def getInput(textFile):
    with open(textFile, encoding='utf-8') as f:
        for line in f:
            print(line)

getInput('your_file.txt')

Whenever you need to debug, you need to change the path of the file to open it in debug mode by simply:每当您需要调试时,您只需更改文件的路径以在调试模式下打开它:

  1. Going to the explorer去探险家
  2. Right click on the file and click on copy relative path右键单击文件,然后单击复制相对路径
  3. Put that path in open把那条路打开

That should help you!那应该对你有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM