Daniel
Daniel

Reputation: 239

find the new path after using os.system('cd')

I'm trying to generate windows CMD using os. After I change the directory using os.system('cd other_dir'), how can I find the new directory, using os?

Upvotes: 0

Views: 926

Answers (3)

Karn Kumar
Karn Kumar

Reputation: 8826

However, other fellows has already suggested the the best possible answers, but i would like to add few more hints while using os module..

>>> import os
>>> os.system("pwd")
/home/digit       # <-- this is listing the present working Dir
0

However its more feasible and wise to the us ethe os modules internal attributes for the usage like traversing into a directory like os.chdir rather using os.system("cd /home/digit/openstack") because it's more intuitive and os module feature.

So, traversing into a directory you should use os.chdir !

>>> os.chdir("openstack")
>>> os.system("pwd")
/home/dgit/openstack
0

Same applied for get the current dir information avoid using native os command while using python os module and rather use os.getcwd.

>>> os.getcwd()
'/home/digit/openstack'

To list the current directory contents use os.listdir rather os.system("ls -l")

>>> os.listdir()
['vm_list.html']

OR, without specifying the current working directory path, this is more pythonic

>>> os.listdir(os.getcwd())
['vm_list.html']

OR, you can even use a for loop to list the files & directory to a specified Dir but more elegant way is above one!

>>> for filename in os.listdir("/home/digit/openstack"):
...     print(filename)
...
vm_list.html

In case you are looking only to get the subdirectories within a given Dir:

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

Upvotes: 0

L&#233;opold Houdin
L&#233;opold Houdin

Reputation: 1525

You can do:

os.getcwd()

This will give you the current working directory (cwd).

Upvotes: 0

Artur
Artur

Reputation: 447

How about standard Linux commands since you're at it:

os.system("pwd")

Upvotes: 1

Related Questions