How to overwrite a text file in Python?

In this tutorial, we will learn how to use Python in order to replace an existing text file with a new file, which might contain different content. In a way, this is similar to creating a Python text file with the same path in your operating system. This tutorial was written on a Windows 11 computer, but it is applicable with very minor adaptations to macOS and Linux operating system.

A word of caution before proceeding: Always ensure that you backup any files before programmatically change them!

Overriding a file with Python

In this first snippet we will replace an existing file with a new one. We start by defining a file path to be override, we then define the file contents (in our case – a single line string object). Then use the TextIOWrapper open function and access the file in write (‘w’) more so we can save the text into our new file.

from pathlib import Path
import datetime

# define directory path and file name
path_dir = Path('C:\WorkDir')
name_file = 'text_file.txt'

# write file contents
file_change_time = datetime.datetime.now()
file_content = "This is our new file. The file was changed at:" + str(file_change_time)
file_path = path_dir.joinpath(name_file)

# overwrite the file
with  open (file_path, 'w') as f:
    f.write('\n'+ file_content)

Notes

  1. In case that the file path specified in the file_path variable doesn’t exist, Python will create the file.
  2. But in case that the Operating system path stored in path_dir doesn’t exist, Python will post a file not found error:
FileNotFoundError: [Errno 2] No such file or directory:
  1. If using the open file function as part of a With block, Python handles the closing of your text file, and there is no need to invoke the close function on every opened file instance.

Replace the file if exists

In order to make our code a little bit more robust we can check whether the directory and file exist:

from pathlib import Path
import datetime

path_dir = Path('C:\WorkDir')
name_file = 'text_file.txt'

# write file contents

file_change_time = datetime.datetime.now()
file_content = "This is our new file. The file was changed at:" + str(file_change_time)
file_path = path_dir.joinpath(name_file)

#ceck if directory and file exist - create or replace the text file
if path_dir.is_dir():
    if file_path.is_file():
        with  open (file_path, 'w') as f:
            f.write('\n'+ file_content)
            print ("Your text file was replaced.")
    else:
        print("The specified file didn't exist. We created a new file.")
else:
    print("The specified directory doesn't exist.")

Replace multiple files in a directory

A more interesting use case is to overwrite multiple text or csv files in an operating system directory. Consider the following snippet:

import glob
import datetime

#define a work directory
path_dir = 'C:\WorkDir\WorkFolder'

# define new file contents
file_change_time = datetime.datetime.now()
file_content = "This is our new file. The file was changed at:" + str(file_change_time)


#define text files to replace
csv_list  =  glob.glob(path_dir+'\\*.txt')

# replace the text files
for file in csv_list:
    with open (file, 'w') as f:
        f.write(file_content)

Suggested learning

How to create new csv files on Windows using Python3?