Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change directory with python

Tags:

python

bash

I coincidentally found out that I cannot change the actual directory from within a python-code. My Test-Program is as follows:

from os import system

def sh(script):
    system("bash -c '%s'" % script)

sh("cd /home")
sh("pwd")

The output of pwd is not /home, but the directory where the code above lives.

Can someone explain why this happens?

like image 267
Tengis Avatar asked Dec 05 '12 20:12

Tengis


People also ask

How do I change directory in Python terminal?

You can change the directory by just typing "cd DirectoryPath" into the command prompt. Replace "DirectoryPath" with either a full path or the name of a folder in the current folder to go into that folder. You can type "cd .." to "up" or "out of" the current directory.

How do I move a file to another directory in Python?

move() method move Files in Python using the. The shutil. move() method takes two arguments first one is the complete source path and the second one is the destination path (including the file/folder name to move), the move function will move the file from source to the destination.

How do I move a folder to another directory in Python?

move() method Recursively moves a file or directory (source) to another location (destination) and returns the destination. If the destination directory already exists then src is moved inside that directory. If the destination already exists but is not a directory then it may be overwritten depending on os.


1 Answers

The problem is that you execute shell commands instead of actually changing the directory using os.chdir()

Each os.system() call executes the given command in a new shell - so the script's working directory is not affected at all.

like image 178
ThiefMaster Avatar answered Sep 16 '22 23:09

ThiefMaster