Creating and saving files in a new directory in Python

Money and Business

The following sections explain how to create and save a new file in Python using a new directory (folder) as the destination.

  • Error when specifying a non-existent directory with open()(FileNotFoundError)
  • os.makedirs()Create a directory
  • Example code to create a new file with a destination

The following is an example of a text file.

When storing images, it depends on the library whether you can specify a path that includes a non-existent directory (or whether it will automatically create one if it does not exist).
FileNotFoundErrorIf this error occurs, you can create a new directory with os.madeirs() before executing the function to save, as in the following example.

Error when specifying a non-existent directory with open()(FileNotFoundError)

When creating a new file with the built-in function open(), an error occurs if a path containing a new directory (a directory that does not exist) is specified as the first argument as the destination.(FileNotFoundError)

open('not_exist_dir/new_file.txt', 'w')
# FileNotFoundError

The first argument of open() can be an absolute path or a path relative to the current directory.

For the basic usage of open(), such as creating a new file in an existing directory, or overwriting or appending to an existing file, refer to the following article.

Create a directory(os.makedirs())

When creating a new file in a non-existent directory, it is necessary to create the directory before open().

If you are using Python 3.2 or later, it is convenient to use os.makedirs() with the argument exist_ok=True. Even if the target directory already exists, no error will occur and the directory can be created at once.

import os

os.makedirs(new_dir_path, exist_ok=True)

If you have an older version of Python and do not have the argument exist_ok in os.makedirs(), you will get an error if you specify the path to a directory that exists, so use os.path.exists() to check for the existence of the directory first.

if not os.path.exists(new_dir_path):
    os.makedirs(new_dir_path)

See the following article for details.

Example code to create a new file with a destination

The following is a code example of a function that creates and saves a new file by specifying the destination directory.

The first argument dir_path is the path of the destination directory, the second argument filename is the name of the new file to be created, and the third argument file_content is the content to be written, each specified as a string.

If the specified directory does not exist, create a new one.

import os

def save_file_at_dir(dir_path, filename, file_content, mode='w'):
    os.makedirs(dir_path, exist_ok=True)
    with open(os.path.join(dir_path, filename), mode) as f:
        f.write(file_content)

Use as follows.

save_file_at_dir('new_dir/sub_dir', 'new_file.txt', 'new text')

In this case, the file new_file.txt with the content “new text” will be created in new_dir\sub_dir. In other words, the following file will be newly created.new_dir/sub_dir/new_file.txt

Concatenating directory and file names with os.path.join().

Also, the mode of open() is specified as an argument. For text files, the default 'w' is fine, but if you want to create a binary file, set mode='wb'.