简体   繁体   English

在python中,os.chdir()无法使用相对路径

[英]In python os.chdir() is not working with relative path

I want to change the working directory in python using os.chdir() from the current project folder to an existing folder in the project folder but it shows a file not found error. 我想使用os.chdir()将python中的工作目录从当前项目文件夹更改为项目文件夹中的现有文件夹,但是它显示文件未找到错误。

import os

print(os.getcwd())

os.chdir("../NewDirectory/") #Error here

print(os.getcwd())

I expected an output: 我期望输出:

C:\Users\John Doe\PycharmProjects\untitled
C:\Users\John Doe\PycharmProjects\untitled\NewDirectory

But I got the result: 但是我得到了结果:

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/'

You say that NewDirectory exists inside untitled which is the current directory. 您说NewDirectory存在于当前目录untitled内。

Then your relative path ../NewDirectory is incorrect because it attempts to find NewDirectory inside the parent of the current directory. 然后您的相对路径../NewDirectory不正确,因为它试图在当前目录的目录中查找NewDirectory That is, it attemps to find NewDirectory inside PycharmProjects ; 也就是说,它attemps找到NewDirectoryPycharmProjects ; which doesn't exist. 不存在。

Replacing your call with os.chdir("NewDirectory") should work as expected. os.chdir("NewDirectory")替换呼叫应该可以正常工作。 "NewDirectory" by itself is a relative path and refers to a directory inside the current one. "NewDirectory"本身是一个相对路径,是指当前目录中的目录。

If you want to make it more explicit, you can write it as os.chdir("./NewDirectory") , which emphasises the fact that NewDirectory is located inside the current directory ( . ). 如果要使其更明确,可以将其编写为os.chdir("./NewDirectory") ,它强调了NewDirectory位于当前目录( . )内部的事实。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM