How to create a file in Python

Posted in Python by Dirk - last update: Feb 07, 2024

The most common approach to create a file in Python is to use the open() function, with the desired mode (w for write, x for exclusive creation, or a for append), and write or read as needed.

Using open() with ‘w’ or ‘x’ mode:

You can use the open()’ function with the w (write) or x (exclusive creation) mode to create a new file or overwrite an existing file.

The difference between w and x: ,

  • ‘w’ (write): Opens a file for writing. If the file exists, it truncates it to zero length (= overwrite the existing file); if the file does not exist, it creates a new file.
# Creating a new file or overwriting an existing file
with open('example.txt', 'w') as file:
    file.write('Hello, this is a new file!')
  • ‘x’ (exclusive creation): Opens a file for exclusive creation. If the file already exists, the operation fails with a FileExistsError. It’s useful when you want to ensure that the file doesn’t exist before creating it.
try:
    with open('example.txt', 'x') as file:
        file.write('Hello, this is a new file!')
except FileExistsError:
    print("File already exists. Cannot create a new file with 'x' mode.")

In the example above - the program tries to create a new file example.txt. If the file exists, it prints an error

Using open() with ‘a’ mode:

The a (append) mode can be used to create a new file or open an existing file for appending data at the end. If the file already exists, data will be appended to the file, keeping the existing data. If the file doesn’t exist, a new file will be created

# Creating a new file or appending to an existing file
with open('example.txt', 'a') as file:
    file.write('\nAppending more data to the file.')

Using open() with ‘w+’ or ‘r+’ mode:

You can use w+ (write and read) or r+ (read and write)** mode to create a new file or open an existing file for both reading and writing.

-‘w+’ (write and read): Opens a file for both writing and reading. If the file already exists, it truncates the file to zero length and starts writing from the beginning (overwriting existing date). If the file does not exist, it creates a new file. Example

with open('example.txt', 'w+') as file:
    file.write('Hello, this is a new file!')
    file.seek(0)  # Move the cursor to the beginning
    content = file.read()
    print(content)

with open('example.txt', 'w+') as file:
    file.write('Trying to add a line')
    file.seek(0)  # Move the cursor to the beginning
    content = file.read()
    print(content)

Will result in the following example.txt:

Trying to add a line

The first content (‘Hello, this is a new file’) is overwritten

-r+’ (read and write): Opens a file for both reading and writing without truncating the file. If the file does not exist, it raises a FileNotFoundError.

with open('example.txt', 'r+') as file:
    content = file.read()
    print("Read content:", content)
    file.write('\nAppending more data to the file.')

If the example.txt does not exist

Traceback (most recent call last):
  File "myprogram.py", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'example.txt'

To handle r+ mode gracefully, you can use a combination of try and except blocks to catch potential exceptions and handle them appropriately. For example, you might want to check whether the file exists before attempting to read or write to it. Here’s an example:

try:
    with open('example.txt', 'r+') as file:
        content = file.read()
        print("Current content:", content)

        # Perform operations with existing content

        file.seek(0)  # Move the cursor to the beginning if you want to overwrite or append
        file.write('Appending more data to the file.')

except FileNotFoundError:
    print("File not found. Creating a new file.")
    with open('example.txt', 'w') as file:
        file.write('Creating a new file with initial content.')

except Exception as e:
    print(f"An error occurred: {e}")

In this example:

  • The try block attempts to open the file in r+ mode and perform read operations.
  • If the file does not exist, it catches a FileNotFoundError and creates a new file with initial content in w mode.
  • If any other exception occurs during file handling, it catches the generic Exception and prints an error message.

This way, you can handle different scenarios gracefully, such as creating a new file if it doesn’t exist or handling other unexpected errors during file operations. You can adjust the error handling based on your specific needs.

Using os module

The os module’ provides functions to interact with the operating system, including file operations.

import os

file_path = 'example_os.txt'

# Create a new file or overwrite an existing file
with open(file_path, 'w') as file:
    file.write('Creating a file using os module.')

To avoid overwriting an existing file when using the os module, you can check whether the file already exists before attempting to create it. You can use the os.path.exists() function to check if a file or directory exists at a given path. If the file exists, you can choose to handle it in a way that suits your specific requirements, such as renaming the file or displaying an error message.

example:

import os

file_path = 'example_os.txt'

# Check if the file already exists
if not os.path.exists(file_path):
    # Create a new file
    with open(file_path, 'w') as file:
        file.write('Creating a new file using os module.')
else:
    print(f"The file '{file_path}' already exists. Choose a different file name.")

In this example, before attempting to create the file, it checks whether the file already exists using os.path.exists(). If the file does not exist, it proceeds to create the new file. Otherwise, it prints a message indicating that the file already exists, and you may want to choose a different file name or handle the situation according to your needs (or do something else, depending on your requirements)

Using Path from pathlib module:

The pathlib module provides an object-oriented interface for file system paths, and you can use it to create files.

In the pathlib module, the Path.touch() method is used to create an empty file or update the access and modification times of an existing file. If the file already exists, it will be updated to have the current timestamp. If the file does not exist, a new empty file will be created.

from pathlib import Path

# Define the file path
file_path = Path('example_pathlib.txt')

# Create an empty file or update the timestamp if the file already exists
file_path.touch()

# Now you can open the file and write content to it
with open(file_path, 'w') as file:
    file.write('Creating a file using pathlib.')

Using Path.touch() is a convenient way to ensure that a file exists at a given path, and it simplifies the process of creating an empty file before performing additional file operations.

Other articles