How to Convert a Text File to a CSV File in Python?

5/5 - (1 vote)

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:

  1. (Optional in shell) pip install pandas
  2. import pandas as pd
  3. df = pd.read_csv('my_file.txt')
  4. df.to_csv('my_file.csv', index=None)

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.txt' and '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.

Enjoy your day, my beautiful friend!