How to Convert a Text File to CSV using Python

In this tutorial, you will learn how to convert a text file to a CSV file using Python and pandas.

TLDR solution

txt2csv.py
import pandas as pd

df = pd.read_csv("path-to-file/file-name.txt")
df.to_csv("target-path/file-name.csv", index=False)

Step-by-Step Example

Step 1: Install the pandas Package

If you don't have pandas already installed, execute the following command in your terminal:

pip install pandas

Step 2: Convert a Text File to a CSV File

Let's say, you have the following text file on your desktop:

fish.txt
Fish,Egg_Count
salmon,5000
pufferfish,200
shark,2

You can convert txt file using pandas as follows:

txt2csv.py
import os
import pandas as pd

desktop_path = os.path.expanduser("~/Desktop")

df = pd.read_csv("desktop_path" + "/fish.txt", sep=",")
df.to_csv("desktop_path" + "/fish.csv")

After you run the script you will find a CSV file on your desktop. Note that the sep option of the read_csv function specifies the character that separates elements within your text file. Thus, always have a look at your text file first and then set the sep option accordingly.

That's it! You just converted a text file using Python.