1

I am executing an imported method in my Python program which generates a bunch of files in the current directory. When I execute it I want to stay in the current directory and instead want it to generate the files in a different directory that I make on the fly, without changing to this directory using os.chdir. What I currently have is that I make the dir, then I change to it using os.chdir and finally change back to the base dir.

Let's say cwd is /home/user/project/, I create /home/user/project/uploads/files/ the files directory is created in the uploads dir and the files are subsequently generated here here. Lastly I switch back to the base dir /home/user/project/

base_dir = os.getcwd()
os.mkdir("/home/user/project/uploads/files/")
os.chdir("/home/user/project/uploads/files/")
method()
os.chdir(base_dir)
    

Is there a more efficient way to do this? Thanks in advance.

user21398
  • 419
  • 6
  • 13
  • 1
    `os.mkdir('path/to/destination')` – watch-this Jan 19 '21 at 00:34
  • @bullseye Sure, but I would then want to generate the files in this directory, _whilst_ staying in the base dir. So the last 3 lines basically is what I am trying to optimize, where method() is the imported function that generates the files in the current directory. Is there a way to do this more efficiently without `os.chdir` to the created dir and then back to `base_dir`? – user21398 Jan 19 '21 at 00:44
  • 1
    What do you mean by generate files? Can you edit the question and provide a full example? – watch-this Jan 19 '21 at 00:49
  • It sounds like to get the behavior you want, you need to modify your method that creates the files to accept a path, rather than automatically creating files in the current directory – jdaz Jan 19 '21 at 00:57
  • @bullseye The imported method() function generates a bunch of files with .pdb extension in the working dir. There's nothing wrong with this code per se, since it works. But I was just wondering if there's a shorter way to do it where I don't need to change directories at all and can execute the code and the files will appear in the created files/ directory. Because the imported method() function does not take a path parameter, it just always generates the files in the working dir. – user21398 Jan 19 '21 at 00:57
  • @jdaz That's what I was thinking of as well, but unfortunately does not accept a path parameter. – user21398 Jan 19 '21 at 01:01
  • Rewrite `method()` to accept a directory as a parameter ... – tink Jan 19 '21 at 01:25
  • Does this answer your question? [How do I change directory back to my original working directory with Python?](https://stackoverflow.com/questions/299446/how-do-i-change-directory-back-to-my-original-working-directory-with-python) – mkrieger1 Jan 19 '21 at 02:00

0 Answers0