当我通过Visual Studio Code加载文件时,VScode找不到目录。
我可以运行代码而不会出现终端问题,结果是:
young@young-desktop:/media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials/10_RNN/ChatBot$ python text_load_text.py
['fij\n', 'feijfaef\n', 'ef\n', 'awef\n', 'awe\n', 'g\n', 'aweg\n', 'ae\n', 'wg\n', 'awe\n', 'h\n', 'aw\n', 'h\n', 'aw\n', 'ef\n', 'aweg\n', 'wea\n', 'gaw\n', 'eg\n', '\n']
但是使用VScode:
young@young-desktop:/media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials$ cd /media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials ; env "PYTHONIOENCODING=UTF-8" "PYTHONUNBUFFERED=1" /home/young/anaconda3/bin/python /home/young/.vscode/extensions/ms-python.python-2018.6.0/pythonFiles/PythonTools/visualstudio_py_launcher.py /media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials 39707 34806ad9-833a-4524-8cd6-18ca4aa74f14 RedirectOutput,RedirectOutput /media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials/10_RNN/ChatBot/text_load_text.py
Traceback (most recent call last):
File "/media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials/10_RNN/ChatBot/text_load_text.py", line 8, in <module>
with open('test.txt', 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
什么原因导致此问题?
test.txt文件最初旨在位于./data/test.txt
所以我测试了
with open('./data/test.txt', 'r') as f:
但是使用VScode失败
因此,我尝试通过以下操作将test.txt文件移至工作目录:
with open('test.txt', 'r') as f:
和
with open('./test.txt', 'r') as f:
但是全部都因VScode而失败。
答案 0 :(得分:2)
更好的解决方案是,首先获得当前目录位置,然后将其与文件的相对路径连接起来。
from os.path import dirname, join
current_dir = dirname(__file__)
file_path = join(current_dir, "./test.txt")
with open(file_path, 'r') as f:
答案 1 :(得分:1)
打开该项目时,我将其打开为“ TensorFlow-Tutorials”文件夹。
所以我的工作目录是:
young@young-desktop:/media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials
所以“。”指示TensorFlow-Tutorials路径
因此,以下路径找不到文件
with open('./test.txt', 'r') as f:
解决方案正在添加其他部分以准确指示我的实际目标目录:
with open("./10_RNN/ChatBot/test.txt", 'r') as f:
x = f.readlines()
print(x)
答案 2 :(得分:0)
尝试在VScode中运行python脚本时,我遇到了相同的问题。原来,我需要使用的功能是context.Response.Body = new MemoryStream(Encoding.UTF8.GetBytes(DateTime.Now.ToString()));
,而 不是 os.chdir('path')
此问题特定于VScode。 VScode将脚本运行在错误的目录之外。我使用sys.path.append('path')
找出了它所在的目录,然后相应地更改了目录。这是帮助我解决此问题的代码片段。
print(os.listdir())
答案 3 :(得分:0)
确保您在终端或命令提示符下位于.txt
文件所在的目录中。
在终端机cd
中进入包含text
文件和.py
文件的目录,运行该程序,它应该可以正常工作。
答案 4 :(得分:0)
只需将txt文件放在运行代码的.py文件所在的文件夹中即可。
即我的代码在dile.py中,该文件位于“ python程序”文件夹中。将txt文件放在该文件夹中
答案 5 :(得分:0)
试试这个:在你的 VSCode python 设置中启用以下选项
在终端执行文件时,是否使用文件所在目录执行,而不是当前打开的文件夹