You can convert a text file to a CSV file in Python in four simple steps: (1) Install the Pandas library, (2) import the Pandas library, (3) read the CSV file as DataFrame, and (4) write the DataFrame to the file:
- (Optional in shell)
pip install pandas
import pandas as pd
df = pd.read_csv('my_file.txt')
Here’s a minimal example:
import pandas as pd read_file = pd.read_csv('my_file.txt') read_file.to_csv ('my_file.csv', index=None)
Of course, replace the filenames
'my_file.csv' with the path and name to your specific in and out files.
🌍 Related Tutorial: Python Convert String to CSV File
Also, you may be interested in our ultimate guide to converting CSVs back to various other formats.
In case you want to merge multiple text files into a single CSV, check out this guide with a quick hack.
In case you have a specific problem with server logs, e.g., you want to convert a server log to a CSV or Excel file, check out this guide on the Finxter blog.
Enjoy your day, my beautiful friend!
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 that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a 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.