简体   繁体   English

为什么 os.chdir() 在这种情况下不能更改目录?

[英]Why os.chdir() cant change dir in this case?

----input - - 输入

print(os.getcwd(), '\n')
print(os.listdir(), '\n')

Gui_path = '/Gui'

os.chdir(Gui_path)

----output - - 输出

C:\Users\vhass\Documents\Coding Projects\The vault C:\Users\vhass\Documents\Coding Projects\The Vault

C:\Users\vhass\Documents\Coding Projects\The vault C:\Users\vhass\Documents\Coding Projects\The Vault

['application.py', 'crypto.py', 'encrypting.py', 'genaccount.py', 'Gui', 'Home.py', 'icons', 'login.py', 'main.py', 'Pics', 'test.py', 'Usernamepass.py', ' pycache '] ['application.py'、'crypto.py'、'encrypting.py'、'genaccount.py'、'Gui'、'Home.py'、'icons'、'login.py'、'main.py' , '图片', 'test.py', 'Usernamepass.py', ' pycache ']

Traceback (most recent call last): File "C:\Users\vhass\Documents\Coding Projects\The vault\login.py", line 19, in os.chdir(Gui_path) FileNotFoundError: [WinError 2] The system cannot find the file specified: '/Gui' Traceback(最近一次调用最后一次):文件“C:\Users\vhass\Documents\Coding Projects\The vault\login.py”,第 19 行,在 os.chdir(Gui_path) FileNotFoundError: [WinError 2] The system cannot find指定的文件:'/ Gui'

note **** The path in this project is not static and might be changed based on user preference, so I can not use the full path.注意 **** 本项目中的路径不是 static,可能会根据用户偏好进行更改,所以我不能使用完整路径。

The issue is that you're providing a full path and not a relative one.问题是您提供的是完整路径而不是相对路径。 os.chdir('/Gui') is trying to go to your root directory ( / ) and look for a folder Gui there. os.chdir('/Gui')正在尝试 go 到您的根目录 ( / ) 并在那里查找文件夹Gui

I think what you're trying to do is look for the folder Gui relative to the current directory.我认为您要做的是查找相对于当前目录的文件夹Gui Try something like尝试类似的东西

>>> import os
>>> os.getcwd()
'/Users/tyler/tmp/stackoverflow'
>>> os.listdir()
['a', 'f', 'Gui', 'c', 'd', 'e', 'b']
>>> os.chdir(os.getcwd() + '/Gui') # <- This is the important line
>>> os.getcwd()
'/Users/tyler/tmp/stackoverflow/Gui'
>>> os.listdir()
['HELLO']
>>>

See how we're doing a string join of os.getcwd() + '/Gui' rather than just '/Gui' ?看看我们如何进行os.getcwd() + '/Gui'而不仅仅是'/Gui'的字符串连接? That ensures we're looking within the directory that we're currenly in.这确保我们正在查看我们当前所在的目录。

You should also take a look at the stdlib pathlib for other helpful primitives, and to ensure that your code handles weird file system edge cases.您还应该查看 stdlib路径库以了解其他有用的原语,并确保您的代码处理奇怪的文件系统边缘情况。

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

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