Python File Operations (with Examples)

In this tutorial, we will explore how to perform various file handling operations in Python with the help of examples. In addition to reading and writing to files in Python, we can also perform several operations, such as creating, appending, renaming, deleting, etc. on files in Python. Let’s understand first creating a file in Python.

How to Create a File in Python?


Creating a file in Python is simple and straightforward. We can simply create a file by opening it in the write ‘w’ mode using open() function. If the file does not exist, it will create a new file. If the file does exist, opening it in write ‘w’ mode will overwrite the existing file. Here’s a simple example that demonstrates how to create a file and write some text to it:

Example 1:

# Specify the name of the file
filename = 'example.txt'

# Create a file by opening it in writing mode. If the file does not exist, it will be created.
with open(filename, 'w') as file:
    # Write a line of text to the file
    file.write('Hello, World!\n')

Content written to the “example.txt” file is as:

Hello, World!

In this example code, we have created a file named example.txt in write mode (‘w’), which means any existing file with the same name will be overwritten. Then, we have written the text “Hello, World!\n” to the file. Closing of file is automatically done by the with statement.

Remember, using the with statement for file operations in Python is a good practice because it automatically closes the file after the block of code is executed, even if an error occurs within the block.

How to Append Data to a File in Python?


Appending data to a file in Python is straightforward. We can do it using the built-in open() function in append access mode ‘a’. When we open a file in append access mode, the file pointer is placed at the end of the file.

Any data written to the file is automatically added at the end of the file without altering the existing content. If the specified file does not exist, Python creates a file and append (i.e. add) data sequentially.


Here’s a simple example demonstrating how to append data to a file in Python:

Example 2:

# Specify the name of the file we want to open.
file_name = 'friends.txt'
# Open the file in write access mode.
with open(file_name, 'w') as file:
    # Write the names to the file.
    file.write("Sanjay Mehra\n")
    file.write("Ravi Mehta\n")
    file.write("John Mathur\n")

# Read the file content after writing.
with open(file_name, 'r') as file:
    print(file.read())
Output:
       Sanjay Mehra
       Ravi Mehta
       John Mathur

Now suppose we want to append or add two more friend names to “friends.txt” file. To do this, we will have to open the file in append access mode ‘a’ only. That is, we have to change only the open() function’s access mode. Look at the below example code.

# Specify the name of the file we want to open.
file_name = 'studentinfo.txt'
# Open the file in  append access mode.
with open(file_name, 'a') as file:
    # Append two friend names to the existing file.
    file.write("Sanjana Gupta\n")
    file.write("Jaanvi Kapoor\n")

# Read the file content after writing.
with open(file_name, 'r') as file:
    print(file.read())
output:
       Sanjay Mehra
       Ravi Mehta
       John Mathur
       Sanjana Gupta
       Jaanvi Kapoor

In this example, we have opened “friends.txt” file in append mode using ‘a’ as the mode argument in the open() function. Then, we have written two more friend names into the text file using write() method. The file is automatically closed when exiting the with block.


Lastly, the code opens the file again in read mode (‘r’) to display its contents after appending on the console. Note that, if you run this program code multiple times, the contents will append to the file each time, adding to whatever content was previously there.

How to Rename a File in Python?


The os module in Python offers several functions that help to perform various operations like renaming and deleting files. To use this module, we first need to import it and then we can call any functions offered by os module. To rename an existing file in Python, we can use the rename() function provided by the os module.

This function takes two arguments: the current name (path) of the file and the new name (path) you want to give the file. The basic syntax of rename() function is as:

os.rename(current_filename, new_filename)

Here’s an example demonstrating how to rename a file:

Example 3:

# Importing os module.
import os
# Define the current file name and the new file name
current_file_name = 'example.txt'
new_file_name = 'renamed_example.txt'

# Check if the current file exists to avoid FileNotFoundError
if os.path.exists(current_file_name):
    # Rename the file from example.txt to renamed_example.txt.
    os.rename(current_file_name, new_file_name)
    print(f"File renamed from '{current_file_name}' to '{new_file_name}' successfully.")
else:
    print(f"The file '{current_file_name}' does not exist.")
Output:
      File renamed from example.txt to renamed_example.txt successfully.

In this example, we have used the os.rename() function to rename a file from example.txt to renamed_example.txt. Before attempting to rename the file, the os.path.exists() function checks if the original file (example.txt) exists to prevent a FileNotFoundError exception. If the file exists, it is renamed; otherwise, a message indicating the file does not exist is displayed on the console.

How to Delete a File in Python?


To delete a file in Python, we can use remove() method available in os module. This function receives one argument, which is the name of file to be deleted. It allows us to delete a specific file by specifying its path. The general syntax of remove() function is as follows:

os.remove(filename)

It’s important to handle exceptions when performing operations like deleting files, as attempting to delete a file that doesn’t exist will raise a FileNotFoundError exception. Here’s a simple example on how to delete a file:

Example 4:

# Importing os module.
import os
# Specify the file name (or path if the file is in a different directory).
file_name = 'renamed_example.txt'

# Check if the file exists to avoid FileNotFoundError exception.
if os.path.exists(file_name):
    # Delete the file
    os.remove(file_name)
    print("The file '%s' has been deleted." % file_name)
else:
    print("The file '%s' does not exist." % file_name)
Output:
       The file 'renamed_example.txt' has been deleted.

In this example, we have used os.path.exists() to check if the file actually exists before attempting to delete a file named renamed_example.txt. If the file exists, it proceeds to delete the file with os.remove() function. If the file does not exist, it prints a message on the console.

Directory Operations in Python


In the previous section, we have learned how to manipulate a file in Python. Now let’s move on to directories. A directory is a basically folder which is used to organize files in our file system. All files are saved in various directories. Python provides efficient methods for handling directories. Python’s os module has several methods that allow us to create, remove, and navigate directories. Let’s see one by one.

How to Create Directory in Python?


To create a directory in Python, we can use the mkdir() function available in the os module. This function allows us to create a single directory. The mkdir() function takes an argument which contains the name of the directory to be created. The basic syntax of mkdir() method is as:

os.mkdir(directory_name)

Here’s an example of how to create a directory using mkdir():

Example 5:

# Importing os module.
import os
# Specify the directory name
dir_name = 'music_directory'

# Check if the directory already exists to avoid FileExistsError
if not os.path.exists(dir_name):
    # Create a new directory named music_dicrectory.
    os.mkdir(dir_name)
    print("Directory '%s' created." % dir_name)
else:
    print("Directory '%s' already exists." % dir_name)
Output:
        Directory 'music_directory' created.

The above example code creates a new directory named “music_directory” in the current location.

How to Change Working Directory in Python?


To change the current working directory in Python, we can use the chdir() function provided by Python’s os module. This function changes the current working directory to the path specified. The chdir() function takes an argument, which is the name of directory that we want to make the current directory. The basic syntax of chdir() method is as:

os.chdir(dir_name)

Here’s a simple example of how to change the current working directory:

Example 6:

# Importing os module.
import os
# Specify the new directory path
new_directory = '/home/directory'

try:
    # Change the current working directory
    os.chdir(new_directory)
    print("Successfully changed the working directory to '%s'" % new_directory)
except FileNotFoundError:
    print("The directory '%s' does not exist" % new_directory)
except Exception as e:
    print("Error changing directory: %s" % e)
Output:
       The directory '/home/directory' does not exist

How to Remove a Directory in Python?


To remove a directory in Python, we can use rmdir() function available in Python’s os module. However, the directory has to be empty for this to work in this case. Let’s take an example of how to remove an empty directory in Python.

Example 7:

# Importing os module.
import os
# Specify the directory name
dir_name = 'music_directory'

try:
    # Remove the empty directory named music_directory.
    os.rmdir(dir_name)
    print("Directory '%s' removed." % dir_name)
except FileNotFoundError:
    print("The directory '%s' does not exist." % dir_name)
except OSError:
    print("The directory '%s' is not empty." % dir_name)
Output:
       Directory 'music_directory' removed.

In this example, we have attempted to remove a directory named music_directory. If the directory does not exist or is not empty, an exception is caught and a message is printed on the console.

However, if you need to remove a directory and all of its contents, you would need to use the rmtree() function of shutil module. You first need to make a directory that contains file and its contents. Let’s take an example program in which we will remove a directory and its contents.

Example 8:

# Importing shutil module.
import shutil
# Specify the directory path
dir_path = 'directory_with_contents'

try:
    # Remove the directory and all its contents
    shutil.rmtree(dir_path)
    print("Directory '%s' and all its contents have been removed." % dir_path)
except FileNotFoundError:
    print("The directory '%s' does not exist." % dir_path)
except Exception as e:
    print("Error removing directory: %s" % e)
Output:
       Directory 'directory_with_contents' and all its contents have been removed.

In this example, we have made a directory named directory_with_contents that contains some contents. Then, we have used rmtree() function of shutil module to remove the directory and its contents. It’s important to note that once the directory and its contents are removed, they cannot be recovered.

Checking File and Directory Information


We can also use Python’s os module to retrieve information about files and directories. Let’s perform it one by one.

Checking if a File or Directory Exists


Before performing any operations on files or directories, it is often good practice to check if they actually exist or not. For this, we can use exists() function from the os.path module. This function returns True if the specified path exists and False otherwise. It works for both files and directories. Here’s a simple example:

Example 9:

# Importing os module.
import os
# Specify the path we want to check
filename = 'example.txt'  # This could be either a file or a directory

# Check if the path exists
if os.path.exists(filename):
    print("The path '%s' exists." % filename)
else:
    print("The path '%s' does not exist." % filename)
Output:
       The path 'example.txt' exists.

In addition to this, if you specifically want to check whether a path is a file or a directory, you can use os.path.isfile(path) for files and os.path.isdir(path) for directories. Here’s an example of how you could use these functions:

Example 10:

# Importing os module.
import os
path = 'studentinfo.txt'

if os.path.exists(path):
    if os.path.isfile(path):
        print("'%s' is a file." % path)
    elif os.path.isdir(path):
        print("'%s' is a directory." % path)
else:
    print("'%s' does not exist." % path)
Output:
        'studentinfo.txt' is a file.

This example first checks if the path exists. If it does, it further checks whether the path is a file or a directory, printing the appropriate message accordingly on the console.


In this tutorial, we have performed different file operations in Python with the help of various example programs. Python offers a rich set of tools for file manipulation and directory operations that allow us to work with the file system in a simple manner.

Always handle files and directories operations carefully, especially when performing deletion operation because they cannot be recovered. Hope that you will have understood the basic file operations in Python and practiced all example programs.
Thanks for reading!!!