How do I create a "cd" command function with Python?

Asked 2 years ago, Updated 2 years ago, 30 views

I'm making a program to draw and save pictures with Python. It's not where the script ran I want to save it somewhere else.

Like cd in the shell How do I change the directory I'm working on?

python cd cwd

2022-09-22 22:28

1 Answers

The working directory (CWD) can be replaced with os.chdir(path)

When I change CWD, It is often used as a way to change the old path (CWD) to a different location (newpath) and then return to the old path.

import os

class chdir(object):
    def __init__(self, newpath):
        self.oldPath = os.getcwd()
        os.chdir(newpath)

    def saveImage(self, img):
        pass #

    def __del__(self):
        os.chdir(self.oldPath) #(Caution) Error if oldPath disappeared during operation.

myClass = chdir("/")
#myClass.saveImage()

*Changing the CWD in the subprocess has no effect on the current process. That is, when you run a Python script that performs os.chdir() in the shell, The CWD in the Python program only changes, but the CWD in the shell does not change.


2022-09-22 22:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.