我想使用 os.chdir() 将 python 中的工作目录从当前项目文件夹更改为项目文件夹中的现有文件夹,但它显示找不到文件错误。
import os
print(os.getcwd())
os.chdir("../NewDirectory/") #Error here
print(os.getcwd())
我期望输出:
C:\Users\John Doe\PycharmProjects\untitled
C:\Users\John Doe\PycharmProjects\untitled\NewDirectory
但是我得到了结果:
C:\Users\John Doe\PycharmProjects\untitled
Traceback (most recent call last):
File "C:/Users/John Doe/PycharmProjects/untitled/miketest.py", line 5, in <module>
os.chdir("../NewDirectory/")
FileNotFoundError: [WinError 2] The system cannot find the file specified: '../NewDirectory/'
最佳答案
你说 NewDirectory
存在于当前目录 untitled
中。
那么您的相对路径 ../NewDirectory
是不正确的,因为它试图在当前目录的 parent 中查找 NewDirectory
。也就是说,它试图在 PycharmProjects
中找到 NewDirectory
;这是不存在的。
用 os.chdir("NewDirectory")
替换您的调用应该会按预期工作。
"NewDirectory"
本身是一个相对路径,指的是当前目录中的一个目录。
如果想更明确一点,可以写成os.chdir("./NewDirectory")
,强调NewDirectory
位于在当前目录中 (.
).
关于python - 在 python 中 os.chdir() 不使用相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55999146/