Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to a new directory in Python without changing directory

Currently, I have the following code...

file_name = content.split('=')[1].replace('"', '') #file, gotten previously
fileName = "/" + self.feed + "/" + self.address + "/" + file_name #add folders 
output = open(file_name, 'wb')
output.write(url.read())
output.close()

My goal is to have python write the file (under file_name) to a file in the "address" folder in the "feed" folder in the current directory (IE, where the python script is saved)

I've looked into the os module, but I don't want to change my current directory and these directories do not already exist.

like image 572
Philip Massey Avatar asked Oct 28 '11 23:10

Philip Massey


People also ask

How do you create a new directory in the current directory in Python?

Use the os. chdir() function to change the current working directory to a new one. Use the os. mkdir() function to make a new directory.

How do I automatically create a directory in Python?

Python's OS module provides an another function to create a directories i.e. os. makedirs(name) will create the directory on given path, also if any intermediate-level directory don't exists then it will create that too. Its just like mkdir -p command in linux.


1 Answers

First, I'm not 100% confident I understand the question, so let me state my assumption: 1) You want to write to a file in a directory that doesn't exist yet. 2) The path is relative (to the current directory). 3) You don't want to change the current directory.

So, given that: Check out these two functions: os.makedirs and os.path.join. Since you want to specify a relative path (with respect to the current directory) you don't want to add the initial "/".

dir_path = os.path.join(self.feed, self.address)  # will return 'feed/address'
os.makedirs(dir_path)                             # create directory [current_path]/feed/address
output = open(os.path.join(dir_path, file_name), 'wb')
like image 62
KP. Avatar answered Sep 24 '22 06:09

KP.