How to read files into a string in Python 3?

In this short Python tutorial we’ll learn how to load the contents one or multiple files (being both text, csv) to a string variable object with Python 3. We will cover several scenarios:

  • Load the content of a single text file.
  • Reading multiple text files in a directory.
  • Reading a csv file.
  • Append the read content to an existing string.

Read contents of a text file to a string

We will first define the path to our file , then check for its existence. Then we’ll use the file IO Wrapper read() method to write the file content into a string variable. Finally we’ll remove unneeded newlines and print the string. Let’s take a look:

from pathlib import Path

# defines the path to the file, replace with a relevant path
file_p = Path('C:\WorkDir').joinpath('file_to_read.txt')

# read the file content into a string
if file_p.is_file():
    with  open (file_p, 'r') as my_file:
        my_text = my_file.read()
else:
    print("Your file doesn't exist")

# getting rid of newlines and print

print( my_text.replace('\n'," "))

Here’s the result we’ll get:

Line number 1 Line number 2

Reading multiple files from a directory

In our second example we’ll loop through all text files (demarcated by the txt suffix) and read them into a list. Finally we’ll convert the list to a string which we can print

import glob

# replace with relevant directory path in your computer
p_dir = 'C:\WorkDir\MyFolder'

txt_files  =  glob.glob(p_dir+'\\*.txt')
mult_text_l = []

# append the different files content to a list

for file in txt_files:
    with open (file, 'r') as f:
        s_text_list = f.read()
        mult_text_l.append(s_text_list)
# convert the list to a string       
text_s = ','.join(mult_text_l)


print( text_s.replace('\n'," "))

Read one or multiple CSV files

If we want to load one or multiple comma separated files (csv) files, we need to do some minor changes to the script that we have posted above:


import glob

# replace with relevant directory path in your computer
p_dir = 'C:\WorkDir\MyFolder'

csv_files  =  glob.glob(p_dir+'\\*.csv')
mult_csv_l = []

# append the different files content to a list

for file in csv_files:
    with open (file, 'r') as f:
        s_csv_list = f.read()
        mult_csv_l.append(s_csv_list)
# convert the list to a string       
csv_s = ','.join(mult_csv_l)


print( csv_s.replace('\n'," "))

Append to an existing string

We might want to read content of one or more files and then append / concatenate it to other string. We’ll use our first script as an example:

from pathlib import Path

# defines the path to the file, replace with a relevant path
file_p = Path('C:\WorkDir').joinpath('file_to_read.txt')

# read the file content into a string
if file_p.is_file():
    with  open (file_p, 'r') as my_file:
        my_text = my_file.read()
else:
    print("Your file doesn't exist")

my_str = "This is my existing string: "
my_text.replace('\n'," ")

# concatenate multiple strings
print( my_str + (my_text.replace('\n'," ")))

Here is our result:

This is my existing string: Line number 1 Line number 2

Let’s keep learning together: