Michael A
Michael A

Reputation: 5840

Creating a file inside a directory in my working directory

I created a directory using:

def createDir(dir_name):
    try:    
        os.mkdir(dir_name)
        return True;
    except:
        return False

createDir(OUTPUT_DIR)

Now I want to create a file for writing and place it inside my newly created directory, that is inside OUTPUT_DIR. How can I do this?

Upvotes: 3

Views: 23681

Answers (2)

garnertb
garnertb

Reputation: 9584

Use the python built-in function open() to create a file object.

import os

f = open(os.path.join(OUTPUT_DIR, 'file.txt'), 'w')
f.write('This is the new file.')
f.close()

Upvotes: 8

Rob Cowie
Rob Cowie

Reputation: 22619

new_file_path = os.path.join(OUTPUT_DIR, 'mynewfile.txt')

with open(new_file_path, 'w') as new_file:
    new_file.write('Something more interesting than this')

Upvotes: 3

Related Questions