0

Hello everyone : I have only one folder under my current directory and I want to go to it by running "cd $(ls)". So I write this code

import os
os.system("cd $(ls)")

But this did not work for me . Anyone can help to write python syntax to go under the only available folder. PS : the name of the folder is changeable that's why I want to use "cd $(ls)"

  • Maybe it did change directory but you don’t know because the `system()` process finished and returned. – Mark Setchell Mar 04 '20 at 13:16
  • Why do you want to use cd? If you make a system call with os then only that system call will have the changed working directory. – steviestickman Mar 04 '20 at 13:20
  • Does this answer your question? [How do I change the working directory in Python?](https://stackoverflow.com/questions/431684/how-do-i-change-the-working-directory-in-python) – Robin Mar 04 '20 at 13:22

3 Answers3

2

The OS module has some utility functions to achieve what you want to do.

  • os.listdir(): return a list with all files/directories inside the current working directory
  • os.chdir(path): changes your working directory

So, you could apply these like:

os.chdir(os.listdir()[0])
1

It is not obvious if by "go to it" you mean "change current directory for the remaining part of script code" or "change directory to be in after the script exits". If the later, you won't be able to do it - os.system starts a subshell, and changes of current directory in a subshell are not propagated to the parent shell. If the former, you should just use:

import glob, os
os.chdir(glob.glob('*')[0])
Błotosmętek
  • 12,717
  • 19
  • 29
0

Use instead:

os.chdir(os.listdir('.')[0])

Although os.system("cd %(ls)) is correctly working in your shell it will not change the current working directory of your running python interpreter, because os.system() is using a separate shell instance that will be destroyed directly after the execution of the cd shell command.

Double check by executing os.getcwd() before and after (os.getcwd() returns the current working directory of your python interpreter).