python - 在 python 中 os.chdir() 不使用相对路径

标签 python

我想使用 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/

相关文章:

python - 为什么 python 不将异常记录到 syslog(但它确实记录了?)

python - Django 1.3 get_absolute_url 和 localeurl

python - 基于ELO的团队匹配算法

python - 创建无法登录的django用户

python - Visual Studio Code : OSError: [Errno 30] Read-only file system while trying to install pylint on Linux Mint

python - 使用某种逻辑从同一索引位置的多个列表中删除所有值

python - QPlainTextEdit 和 QCompleter 焦点问题

python - 在 bash shell 中使用 Python 2.6 从目录中读取文件的正确方法

python - tf.while_loop 仅考虑最后一次迭代

python - 根据另一个列表随机替换字典列表中的元素