0

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?

Daniel
  • 229
  • 1
  • 8
  • `os.system('cd other_dir')` is basically a no-op, since the `cd` is executed in a subshell. The working directory of your program won't change. – Aran-Fey Sep 29 '18 at 10:57

3 Answers3

1

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

os.system("pwd")
Artur
  • 407
  • 2
  • 8
0

You can do:

os.getcwd()

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

Léopold Houdin
  • 1,515
  • 13
  • 18
0

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']
>>>
Karn Kumar
  • 8,518
  • 3
  • 27
  • 53