英文:
Python in VSCode works on file in "old" folder after moving it to sub-folder
问题
在VS Code中,我已经将一个文件夹定义为我的工作区(例如:"/Users/xxxx/Documents/900. PYTHON/# VS Code/Workspace/")。我在那里有一个名为"main.py"的Python代码文件,该文件在同一文件夹中创建并读取名为"exercise_register.csv"的文件。
我创建了一个子文件夹"(...)/Workspace/workouts/",将包含代码的"main.py"文件和"exercise_register.csv"文件都移动到了这个子文件夹中。
现在在运行代码时,我遇到了一个错误:
发生了异常: 文件未找到错误
[Errno 2] 没有这样的文件或目录: 'exercise_register.csv'
File "/Users/xxxx/Documents/900. PYTHON/# VS Code/Workspace/workouts/main.py", line 51, in review_register
with open("exercise_register.csv", "r") as file:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
当我使用下面的代码时,Python会在之前的文件夹中创建新文件,而不是在"(...)/workouts/"文件夹中,也就是"main.py"文件所移动到的文件夹中:
with open("exercise_register.csv", "w") as file:
for line in data:
file.write(line)
有什么建议可以解决这个问题吗?
我希望能够从存储"exercise.py"文件的同一文件夹中打开文件。
我添加了一张图片来展示文件夹结构,以便更好地理解我的情况:
英文:
In VS Code I have a folder defined as my workspace (e.g.: "/Users/xxxx/Documents/900. PYTHON/# VS Code/Workspace/". I had there a file with Python code (main.py) which was creating and reading the file in the same folder. Name of the file which was created is: "exercise_register.csv"
I created a sub-folder "(...)/Workspace/workouts/" where I moved both the "main.py" file with code and "exercise_register.csv" file.
Now I get and error running the code:
Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: 'exercise_register.csv'
File "/Users/xxxx/Documents/900. PYTHON/# VS Code/Workspace/workouts/main.py", line 51, in review_register
with open("exercise_register.csv", "r") as file:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
When I use the below code, Python creates new file in the previous folder, not in the "(...)/workouts/" folder, in which the "main.py" file was moved to.
with open("exercise_register.csv", "w") as file:
for line in data:
file.write(line)
Any suggestions how to solve this?
I expected to have the file opened from the same folder where my "exercise.py" file is stored.
I'm adding a picture showing the folder structure to visualise my case:
答案1
得分: 0
这是由于VSCode将工作区用作根文件夹导致的。
这将导致一个问题。当您在工作区的深目录中使用os.getcwd()
方法时,仍然会获得工作区目录。
您可以打开设置,搜索Python > Terminal: Execute In File Dir,然后进行检查。
您还可以使用调试模式并将以下内容添加到您的launch.json中:
"cwd": "${fileDirname}"
英文:
This is caused by vscode using workspace as root floder.
This will lead to a problem. When you use the os.getcwd()
method in the deep directory of the workspace, you will still get the workspace directory.
You can open your settings and search Python > Terminal: Execute In File Dir then check it.
You can also use Debug mode and add the following to your launch.json:
"cwd": "${fileDirname}"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论