Computing Corn
Computing Corn

Reputation: 137

Python 3: Creating files in relative directories

I want to create a new directory in the same folder as my Python project and want to create a new text file in that place.

How can I do this without using the absolute directory name?

Upvotes: 3

Views: 5201

Answers (1)

amoose136
amoose136

Reputation: 188

Assuming you have the directory of the python project relative to where the script was called from and you also have either the absolute directory you want to create the folder in or it's location relative to where you called the script from, see the following:

import os

rel_directory=os.path.relpath(target_directory,base_directory)

Here the second line returns the relative path from base_directory to target_directory.

If you want the current working directory you could do something like os.path.relpath('.','/') or os.path.realpath('.') or os.getcwd(). Those are all the same if you don't change the current working directory after the start of the script.

From there you can just add the appropriate relative directory in front of the part to open the file.

f=open(rel_directory+'/'+filename,'a')
f.write("some stuff I'm adding to the file")
f.close()

Upvotes: 7

Related Questions