我对编程和vscode非常陌生。
我正在学习Python,目前我正在学习如何使用文件。
路径看起来像这样:/home/anewuser/learning/chapter10。
问题:完全基本的“在python中读取文件”课程在vscode中不起作用,因为在运行位于~/learning/chapter10中的.py文件时会出现no such file or directory错误。但是vscode希望我应该在python中打开的.txt文件在~/learning目录中,然后它就可以工作了。我不喜欢这种行为。
我想要的就是能够读取.py文件所在目录中的文件。该怎么做呢?
发布于 2019-03-17 19:31:33
因为在本例中~/learning是默认的cwd (当前工作目录),所以VSCode会在该位置查找pi_digits.txt。如果将pi_digits.txt放在file_reader.py (位于~/learning/chapter10)旁边,则必须指定路径(通过在.txt文件中添加chapter10/ )。
所以你应该这样做:
with open('chapter10/pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)如果要更改默认的当前工作目录(例如,要将其更改为~/learning/chapter10),则必须执行以下操作:
~/learning/chapter10/file_reader.py
import os # first you need to import the module 'os'
# set the cwd to 'chapter10'
os.chdir('chapter10')
# now 'file_reader.py' and 'pi_digits.txt' are both in the cwd
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)使用os.chdir('chapter10'),您已经将chapter10设置为默认的cwd,现在VSCode将在其中查找pi_digits.txt。
有关os.chdir()的详细信息,您可以通过the official documentation阅读或在stackoverflow上查看this post。
发布于 2020-09-11 00:14:47
在“用户设置”中,使用搜索栏查找"python.terminal.executeInFileDir“,并将其值(=)设置为"true”而不是"false“。
我从这里接受了这个答案这是我第一次把答案放在StackOverflow上,所以如果我没有用正确的方法,我道歉
https://stackoverflow.com/questions/55191397
复制相似问题