Python 使用os.system(';cd';)后查找新路径

Python 使用os.system(';cd';)后查找新路径,python,operating-system,python-os,Python,Operating System,Python Os,我正在尝试使用操作系统生成windows CMD。 在我使用os.system('cd other_dir')更改目录后,如何使用os查找新目录?既然您正在使用标准Linux命令,那么如何使用标准Linux命令: os.system("pwd") 你可以做: os.getcwd() 这将为您提供当前工作目录(cwd)。然而,其他研究员已经提出了最好的答案,但我想在使用os模块时添加一些提示 >>> import os >>> os.system("pwd"

我正在尝试使用操作系统生成windows CMD。
在我使用os.system('cd other_dir')更改目录后,如何使用os查找新目录?

既然您正在使用标准Linux命令,那么如何使用标准Linux命令:

os.system("pwd")
你可以做:

os.getcwd()

这将为您提供当前工作目录(cwd)。

然而,其他研究员已经提出了最好的答案,但我想在使用
os
模块时添加一些提示

>>> import os
>>> os.system("pwd")
/home/digit       # <-- this is listing the present working Dir
0
同样适用于获取当前目录信息,避免在使用python
os
模块时使用本机os命令,而是使用
os.getcwd

>>> os.getcwd()
'/home/digit/openstack'
要列出当前目录内容,请使用
os.listdir
而不是
os.system(“ls-l”)

或者,在不指定当前工作目录路径的情况下,这更像python

>>> os.listdir(os.getcwd())
['vm_list.html']
或者,您甚至可以使用for循环将文件和目录列出到指定的目录,但更优雅的方法是在一个目录之上

>>> for filename in os.listdir("/home/digit/openstack"):
...     print(filename)
...
vm_list.html
如果您只想获取给定目录中的子目录:

>>> os.chdir("/home/digit/plura/Test")

>>> next(os.walk('.'))[1]
['Python_Dump', 'File_Write_Method', 'Python_FTP', 'Python_Panda', 'Python-3.6.3', 'Python_Parsers', 'Python_Mail', 'Python_aritsTest', 'Network_DeOps', 'Python_ldap', 'Python_Ftp', 'Regular_Expr', 'Python_Primer', 'Python_excep', 'dnspython', '.git', 'argpass', 'BASH', 'NWK-old', 'tmp', 'Backup']
>>>
os.system('cd other_dir')
基本上是一个no-op,因为
cd
是在子shell中执行的。程序的工作目录不会更改。
>>> for filename in os.listdir("/home/digit/openstack"):
...     print(filename)
...
vm_list.html
>>> os.chdir("/home/digit/plura/Test")

>>> next(os.walk('.'))[1]
['Python_Dump', 'File_Write_Method', 'Python_FTP', 'Python_Panda', 'Python-3.6.3', 'Python_Parsers', 'Python_Mail', 'Python_aritsTest', 'Network_DeOps', 'Python_ldap', 'Python_Ftp', 'Regular_Expr', 'Python_Primer', 'Python_excep', 'dnspython', '.git', 'argpass', 'BASH', 'NWK-old', 'tmp', 'Backup']
>>>