How to append text to one or multiple files in Python 3?

You have one or multiple files (in either text or comma separated values (csv) format. You would like to use a simple Python snippet in order to programmatically append text into your file/s.

Add text to a file in Python example

In our first example, we’ll show how you can easily open an existing file an add some text to it. We’ll first define the path to the work directory and file name. Then define the text to be added. We then use the open method of our TextIOWrapper and access the file in append mode (‘a’) and write the text at the end of the file.

import os

path_dir = Path('C:\WorkDir')
name_file = 'myfile.txt'
file_path = os.path.join(path_dir, name_file)
my_text = 'Copyright@2022'

with open (file_path, 'a') as f:
    f.write('\n'+ my_text )

Here’s a similar snippet, that uses the path library to define the path to the file that we’ll be changing:

#Add text to specific file

from pathlib import Path

path_dir = Path('C:\WorkDir')
name_file = 'myfile.txt'
file_path = path_dir.joinpath(name_file)
my_text = 'Copyright@2022'

with  open (file_path, 'a') as f:
    f.write('\n'+ my_text)

Append to file if it exists

To make our code a little more robust we’ll first go ahead and check whether the csv or txt file we want to modify exists in our file system:

from pathlib import Path

path_dir = Path('C:\WorkDir')
name_file = 'myfile.txt'
file_path = path_dir.joinpath(name_file)
my_text = 'Copyright@2022'

if file_path.is_file():
    with  open (file_path, 'a') as f:
        f.write('\n'+ my_text)
    print('file modified')
else:
    print('Not possible to append to non existing file')

Append to multiple text or csv files

Our last example in this tutorial will focus on adding some data to multiple files. This will come very handy, as in real world, you will most probably use Python to modify several files and directories concurrently. We’ll use the glob library in order to find the files to modify. In our specific example we’ll look for all occurrences of csv files in a directory and add our copyright note.

Here’s the code:

import glob

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

#define a list of csv files to modify
csv_list  =  glob.glob(path_dir+'\\*.csv')

# iterate through the list and append text to each file
for file in csv_list:
    with open (file, 'a') as f:
        f.write('\n'+ 'Copyright@2022')

Additional learning

How to add new text or csv files with Python?