首页 > 解决方案 > 当我更改目录然后运行 ​​Python 时会发生什么?

问题描述

我看了这么多帖子,我仍然在努力掌握这一点。

testfile.txt 位于 /home/myusername 文件夹中

$ pwd
/home/myusername

$ python3

>>> open('testfile.txt')
#Success

>>> quit()

$ cd folderA
$ python3
>>> open('testfile.txt')
#No such file

// Move testfile to folderA
>>> open('testfile.txt')
#No such file

Try to change directory,
>>> import os
>>> os.chdir("folderA")
>>> open('testfile.txt')
#fail, no such file

所以,我只是想知道这里发生了什么...... 1)当我更改目录时,Python解释器似乎在我更改为的目录中找不到我的文件,甚至在我更改之前它正在工作的主/用户名目录中目录!!2)如果我使用 os 将目录更改为文件夹,这似乎对我没有任何作用。

所以,如果我的步骤是正确的,在终端中更改目录然后运行 ​​python 似乎会扰乱 python 的相对路径所在的位置.. 并且 os.chdir 似乎没有帮助。

仅供参考:我正在从命令提示符运行 Ubuntu(Windows),即使我尝试使用绝对路径“/home/username/folder/file.txt”,它仍然无法正常工作。这是我能做的最好的......请帮忙!

标签: python

解决方案


推荐阅读