You can merge multiple text files to a single CSV file in Python by using the
glob.glob('./*.txt') expression to filter out all path names of text files in a given folder. Then iterate over all those path names and use the
open() function to read the file contents and write append them to the CSV.
Here’s the simple example:
import glob with open('my_file.csv', 'a') as csv_file: for path in glob.glob('./*.txt'): with open(path) as txt_file: txt = txt_file.read() + '\n' csv_file.write(txt)
The resulting output CSV file shows that all text files have been merged:
You can replace the separator (e.g., from single empty space to comma) by using the
txt.replace(' ', ',') function before writing it in the CSV:
import glob with open('my_file.csv', 'a') as csv_file: for path in glob.glob('./*.txt'): with open(path) as txt_file: txt = txt_file.read() + '\n' txt = txt.replace(' ', ',') csv_file.write(txt)
The resulting CSV is neatly separated with comma characters:
In case you need some more advanced ways to convert the text files to the CSV, you may want to check out the Pandas
read_csv() function to read the CSV into a DataFrame.
🌍 Related Tutorial: How to Read a CSV to a DataFrame?
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.