Write a file to a directory that doesnt exist [duplicate]
2024/11/19 3:44:16
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.
Answer
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.5if exc.errno == errno.EEXIST and os.path.isdir(path):passelse: raisedef 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.pathdef 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(...)
I started to learn python a week ago and want to write a small program that converts a email to a image (.png) so that it can be shared on forums without risking to get lots of spam mails.
It seems lik…
I have a large list files that contain 2D numpy arrays pickled through numpy.save. I am trying to read the first column of each file and create a new 2D array.I currently read each column using numpy.…
It is not yet clear for me what metrics are (as given in the code below). What exactly are they evaluating? Why do we need to define them in the model? Why we can have multiple metrics in one model?…
Im using async_engine. When I try to execute anything:
async with self.async_engine.connect() as con:query = "SELECT id, name FROM item LIMIT 50;"result = await con.execute(f"{query}&quo…
Im using @functools.lru_cache in Python 3.3. I would like to save the cache to a file, in order to restore it when the program will be restarted. How could I do?Edit 1 Possible solution: We need to pi…
Does anyone know an algorithm to either calculate the moon phase or age on a given date or find the dates for new/full moons in a given year?Googling tells me the answer is in some Astronomy book, but…
In my Flask-RESTful API, imagine I have two objects, users and cities. It is a 1-to-many relationship. Now when I create my API and add resources to it, all I can seem to do is map very easy and genera…
Django 1.6I have a working block of code in a Django form class as shown below. The data set from which Im building the form field list can include an initial value for any of the fields, and Im having…
I have a lot of simple scripts that calculate some stuff or so. They consist of just a single module.Should I write main methods for them and call them with the if __name__ construct, or just dump it a…
It seems scipy once provided a function mad to calculate the mean absolute deviation for a set of numbers:http://projects.scipy.org/scipy/browser/trunk/scipy/stats/models/utils.py?rev=3473However, I c…