Alex Rivera | Logout

Writing to a new directory in Python without changing directory

Asked 2011-10-28T23:44:31.383
14

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.

Edit
Report

2 Answers

10

This will create the file feed/address/file.txt in the same directory as the current script:

import os

file_name = 'file.txt'
script_dir = os.path.dirname(os.path.abspath(__file__))
dest_dir = os.path.join(script_dir, 'feed', 'address')
try:
    os.makedirs(dest_dir)
except OSError:
    pass # already exists
path = os.path.join(dest_dir, file_name)
with open(path, 'wb') as stream:
    stream.write('foo\n')
answered 2011-10-29T00:14:32.610
1

Commands like os.mkdir don't actually require that you make the folder in your current directory; you can put a relative or absolute path.

os.mkdir('../new_dir')
os.mkdir('/home/you/Desktop/stuff')

I don't know of a way to both recursively create the folders and open the file besides writing such a function yourself - here's approximately the code in-line. os.makedirs will get you most of the way there; using the same mysterious self object you haven't shown us:

dir = "/" + self.feed + "/" + self.address + "/"
os.makedirs(dir)
output = open(os.path.join(dir, file_name), 'wb')
answered 2011-10-29T00:08:41.207

Your Answer