3

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?

2 Answers 2

8

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() 
Sign up to request clarification or add additional context in comments.

1 Comment

It is better to use os.path.join than + '/' +.
3
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') 

3 Comments

Why >= 2.7? with was introduced in 2.5 (see the docs).
Python 2.5 >>> help("with") no Python documentation found for 'with'
According to the documentation it was introduced in 2.5. I can use it in 2.6. In 2.5 try from __future__ import with_statement.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.