简体   繁体   English

为什么我不能更改当前工作目录?

[英]Why can't I change the current working directory?

I am trying to create my first python program that deletes any empty directories within d:\\source .我正在尝试创建我的第一个 python 程序,该程序删除d:\\source任何空目录。 It appears I can't even enter the directory with my current skills:看来我现在的技能连目录都进不去:

import os
os.getcwd()
os.chdir("D:\\SOURCE")
os.getcwd()

All I get is...我得到的只是...

D:\CODING\venv\Scripts\python.exe D:/CODING/tester.py

Process finished with exit code 0

It seems it has not changed the working dir, how do I verify that?似乎它没有改变工作目录,我该如何验证? Why won't it display the results/errors for the os.chdir("D:\\\\SOURCE") or the second os.getcwd() command at all?为什么它根本不显示os.chdir("D:\\\\SOURCE")或第二个os.getcwd()命令的结果/错误?

Chances are your program indeed changes the directory.您的程序可能确实更改了目录。 But you cannot see this:但是你看不到这个:

  • A mere os.getcwd() won't do anything visible: it retrieves the current working directory and discards it.仅仅os.getcwd()不会做任何可见的事情:它检索当前工作目录并丢弃它。 Instead, you should do print(os.getcwd())相反,你应该做print(os.getcwd())
  • Changing the current working directory only affects the current process (ie, the Python program), but not its parent (the command prompt).更改当前工作目录仅影响当前进程(即 Python 程序),而不影响其父进程(命令提示符)。 So your command prompt keeps its cwd and doesn't inherit the one from the called program.因此,您的命令提示符会保留其 cwd,并且不会从被调用程序继承该 cwd。

You need to print the result.您需要打印结果。

import os
print(os.getcwd())
os.chdir("D:\\SOURCE")
print(os.getcwd())

os.chdir() doesn't return any value . os.chdir()不返回任何值 It will just change the directory.它只会改变目录。 As suggested in other answers you can print/output the current directory using正如其他答案中所建议的,您可以使用打印/输出当前目录

os.chdir("D:\\SOURCE") 
print(os.getcwd())

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

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