根据我在哪个文件夹中打开 vs 代码,在 VS 代码中打开文件或导入模块时出现问题

Trouble with opening files or importing modules in VS code based on which folder I open vs code in

因此,如果我在 vs 代码中打开一个文件夹来存储我需要打开或导入的文件或模块,我的代码可以正常工作,但是如果我打开目录中更高的文件夹,我会收到错误消息,例如 file not找到了。

路径:C:\Users\user1\Desktop\Programming\PythonDaysPython\Day10

我的 .py 文件在第 10 天,如果我在该文件夹中打开 VS 代码,我的程序可以运行,但是如果我在 30DayPython 中打开 VS,它就不起作用。

为什么我必须在我正在处理的文件夹(包含我的文件)中打开 vs,它不应该使用我所在文件的相对路径 运行 而不是我打开 vs 的位置代码来自?

我的代码:

import os

email_txt = os.path.join('templates', 'email.txt')
content = ''

with open(email_txt, 'r') as f:
   enter code herecontent = f.read()
print(content.format(name='Joe'))

在比包含该程序的文件夹高 1 个文件夹中打开 vs code 的图像,它不起作用。

那是因为您当前的工作目录发生了变化。当您打开 30DaysPython 作为当前文件夹时,您必须将路径代码更改为

email_txt = os.path.join('Day10\templates', 'email.txt')

然后错误应该消失了。