简体   繁体   English

引用 Python 中子目录之间文件的正确方法和 VSCode 设置是什么

[英]What's the correct way and VSCode setup to refer to files between subdirectories in Python

I have a folder with a few subfolders as here:我有一个包含几个子文件夹的文件夹,如下所示:

my-project/
  input/
    data.csv
  src/
    script.py

I want to read data from my-project/input/data.csv within script.py , so I have:我想从script.py中的my-project/input/data.csv读取数据,所以我有:

import pandas as pd
data = pd.read_csv('../input/data.csv')

However, my workspace is my-project so when I run script.py it returns:但是,我的工作区是my-project ,所以当我运行script.py它返回:

Exception has occurred: FileNotFoundError [Errno 2] No such file or directory: '../input/data.csv发生异常:FileNotFoundError [Errno 2] 没有这样的文件或目录:'../input/data.csv

which is understandable as input is within my-project , not at the same level.这是可以理解的,因为inputmy-project中,而不是在同一级别。 However, referring with .. really feels like the correct way to refer to data.csv as we do it from script.py .但是,使用..引用确实感觉像是引用data.csv的正确方法,就像我们从script.py中所做的那样。 But maybe I'm wrong?但也许我错了?

In case this is a reasonable way to refer to my data file - how can I setup the VSCode to be able to run the script without returning the error?如果这是引用我的数据文件的合理方法 - 我如何设置 VSCode 以便能够运行脚本而不返回错误? I think there should be a way to add the subfolder to searching path, without needing to open the subfolder as a workspace, but I had a bad luck trying to find it.我认为应该有一种方法可以将子文件夹添加到搜索路径,而无需将子文件夹作为工作区打开,但我运气不好试图找到它。

@Edit: Please note that I'm aware of the concept of relative/absolute paths. @Edit:请注意,我知道相对/绝对路径的概念。 This questions is more about VSCode settings.这个问题更多的是关于 VSCode 设置。 I am also willing to accept the answer: "No, referring with ../input/data.csv is the dumb thing to do in this settings. You should refer with input/data.csv instead, because..." (it's contradictory with my current understanding, but I could be entirely wrong and I'd be happy to learn a different point of view)我也愿意接受答案:“不,使用../input/data.csv在此设置中是愚蠢的做法。您应该使用input/data.csv来代替,因为...”(它是与我目前的理解相矛盾,但我可能完全错了,我很乐意学习不同的观点)

I believe this is simpler than you thought, let do it together!我相信这比你想象的要简单,让我们一起做吧!

  1. 创建空文件夹

  2. 用 VSCode 打开它

The used extensions...使用的扩展...

  1. 扩展

I believe the below steps are not so hard!我相信下面的步骤并不难!

  1. 基本步骤

Switch the default interpreter to the created virtual environment将默认解释器切换到创建的虚拟环境

  1. 虚拟环境

Create a simple launch.json, with simple choice python script创建一个简单的launch.json,用简单的选择python脚本

  1. 创建启动.json

  2. Launch.json 文件示例

Guess what now!猜猜现在怎么样! All we have to do now is select a script.py file in the editor then....... RUN!我们现在要做的就是在编辑器中 select 一个script.py文件然后......运行!

  1. 运行脚本后

You can see the result in the terminal.您可以在终端中看到结果。

let's talk a bit...让我们谈谈...

The generated launch.json file will force us to select the **src.script.py" in the editor before we click the start button every time we want to launch the program, if you like so, I can suggest a more proper way生成的launch.json文件会强制我们在编辑器中select **src.script.py" 在我们每次要启动程序之前点击开始按钮,如果你喜欢,我可以建议一个更合适的方法

In step 6, you can choose Module instead of Python file , after that the editor will prompt you a field asking for the module name, our input must be src.script .在第 6 步中,您可以选择Module而不是Python 文件,之后编辑器会提示您输入模块名称的字段,我们的输入必须是src.script

We will get our launch.json file like this...我们将得到我们的launch.json文件,像这样......

新的launch.json

And now, we can start the program from where we want, which means if the opened file in the editor is "src/data.json" as an example, going to the debugger section and click start will always start the src/script.py file.现在,我们可以从我们想要的地方启动程序,这意味着如果在编辑器中打开的文件是“src/data.json”,例如,进入调试器部分并单击启动将始终启动src/script。 .py文件。

If you run the script in your workspace then input/data.csv should work.如果您在工作区中运行脚本,则input/data.csv应该可以工作。 The location is not based on where your script is, but from where you run it.该位置不是基于您的脚本所在的位置,而是您运行它的位置。

To get the current working directory you can use要获取当前工作目录,您可以使用

import os
print(os.getcwd())

and then go from there.然后从那里开始 go。

Edit: you can change the working directory in your launch.json as described here: https://stackoverflow.com/a/55072246/14246131编辑:您可以更改launch.json中的工作目录,如下所述: https://stackoverflow.com/a/55072246/14246131

by setting launch.json通过设置launch.json

"cwd":"${fileDirname}"

// or use "cwd":"${workspaceFolder}/src" to specifically assign /src as your current working directory

then all the relative path starts from the py file you are running (in your case will be my-project/src ), you should be able to use:然后所有相对路径都从您正在运行的 py 文件开始(在您的情况下是my-project/src ),您应该能够使用:

data = pd.read_csv('../input/data.csv')

the launch.json variables can be referenced here: https://code.visualstudio.com/docs/editor/variables-reference launch.json 变量可以在这里引用: https://code.visualstudio.com/docs/editor/variables-reference


here's my sample env for your reference:这是我的示例环境供您参考:

file structure:文件结构:

my-project/
  .vscode/
    launch.json
  input/
    xxxxx.txt
  src/
    main.py

launch.json:发射.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "cwd":"${fileDirname}"
        }
    ]
}

main.py:主要.py:

with open('../input/xxxxx.txt', 'r') as file_input:
    res = file_input.read()
    print(res)

I would typically do the following -- figure out the directory where my current.py file is and use a relative path from there我通常会执行以下操作 - 找出我的 current.py 文件所在的目录并从那里使用相对路径

import os
py_folder = os.path.dirname(os.path.abspath(__file__))
input_folder = os.path.join(py_folder, '../input')
data = pd.read_csv(os.path.join(input_folder', 'data.csv'))

this way it does not matter from which directory you run your.py, and it works for any development environment ie not VSCode specific这样,您从哪个目录运行 your.py 并不重要,它适用于任何开发环境,即不是 VSCode 特定的

You are probably referring to the file like ../input/data.csv in relation to the path of your script.py您可能指的是与您的script.py路径相关的../input/data.csv之类的文件

But that is not the correct way to go about it you should be adding the file path in relation to from where you are executing the script.py , which I assume is from the root of project folder most probably.但这不是 go 关于它的正确方法,您应该添加与执行script.py的位置相关的文件路径,我假设它最有可能来自项目文件夹的根目录。 Especially if you are using the run python command from VS code.特别是如果您使用 VS 代码中的 run python 命令。

Hence why the path input/data.csv should work in that case.因此,为什么路径input/data.csv应该在这种情况下工作。

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

相关问题 初始化引用文件的实例属性的正确方法是什么? - What's the proper way to initialize instance attributes that refer to files? 在python中引用bazel数据文件的正确方法是什么? - What is the right way to refer bazel data files in python? VSCode 中的 Python:切换到正确环境的最简单方法是什么? - Python in VSCode: What is the easiest way to switch to the correct environment? 在这个 class 中测试这个“setUp()”function 的正确方法是什么? - What's the correct way to test this “setUp()” function inside this class? 在setUp方法中报告Python unittest中的错误的正确方法是什么? - What is the correct way to report an error in a Python unittest in the setUp method? 导入python包的正确方法是什么? - What's the correct way to import a python package? Python:正确引用unicode字符串索引的方法 - Python: Correct Way to refer to index of unicode string 在 .py 文件之间定义全局变量的正确方法是什么 - What is the correct way to define global variables between .py files 在Python中提取正则表达式匹配项的正确方法是什么? - What's the correct way to extract a regexp match in Python? 配置 Python 的 logging.FileHandler 的正确方法是什么? - What is the correct way of configuring Python's logging.FileHandler?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM