Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write file to a directory that doesn't exist

Tags:

python

How do I using with open() as f: ... to write the file in a directory that doesn't exist.

For example:

with open('/Users/bill/output/output-text.txt', 'w') as file_to_write:     file_to_write.write("{}\n".format(result)) 

Let's say the /Users/bill/output/ directory doesn't exist. If the directory doesn't exist just create the directory and write the file there.

like image 572
Billz Avatar asked May 21 '14 21:05

Billz


People also ask

How do you create a file that doesn't exist?

To create a file if not exist in Python, use the open() function. The open() is a built-in Python function that opens the file and returns it as a file object. The open() takes the file path and the mode as input and returns the file object as output.

How do you create a file and the directory if it doesn't exist in Python?

You need to first create the directory. The mkdir -p implementation from this answer will do just what you want. mkdir -p will create any parent directories as required, and silently do nothing if it already exists.

Can you write to a directory?

Directory handles are not writable. If you want to copy the contents of a directory, you will need to copy each file, directory, and link in the source directory individually. To copy each file, you will need to create a new file in the target directory and write the contents of the source file into it.

Which mode create new file if the file does not exist?

"w" - Write - will create a file if the specified file does not exist.


1 Answers

You need to first create the directory.

The mkdir -p implementation from this answer will do just what you want. mkdir -p will create any parent directories as required, and silently do nothing if it already exists.

Here I've implemented a safe_open_w() method which calls mkdir_p on the directory part of the path, before opening the file for writing:

import os, os.path import errno  # Taken from https://stackoverflow.com/a/600612/119527 def mkdir_p(path):     try:         os.makedirs(path)     except OSError as exc: # Python >2.5         if exc.errno == errno.EEXIST and os.path.isdir(path):             pass         else: raise  def safe_open_w(path):     ''' Open "path" for writing, creating any parent directories as needed.     '''     mkdir_p(os.path.dirname(path))     return open(path, 'w')  with safe_open_w('/Users/bill/output/output-text.txt') as f:     f.write(...) 

Updated for Python 3:

import os, os.path  def safe_open_w(path):     ''' Open "path" for writing, creating any parent directories as needed.     '''     os.makedirs(os.path.dirname(path), exist_ok=True)     return open(path, 'w')  with safe_open_w('/Users/bill/output/output-text.txt') as f:     f.write(...) 
like image 141
Jonathon Reinhart Avatar answered Oct 04 '22 04:10

Jonathon Reinhart