Convert Text File to CSV using Python

To convert a text file to a CSV file using Python:

import pandas as pd

read_file = pd.read_csv(r"Path where the Text file is stored\File name.txt")
read_file.to_csv(r"Path where the CSV will be saved\File name.csv", index=False)

Steps to Convert a Text File to CSV using Python

Step 1: Install the Pandas package

If you haven’t already done so, install the Pandas package using this command:

pip install pandas

Step 2: Capture the path where your text file is stored

Next, capture the path where the text file is stored on your computer.

Here is an example of a path where a text file (called ‘Product_List‘) is stored:

C:\Users\Ron\Desktop\Test\Product_List.txt

Where the text file contains the following content:

Product,Price
Laptop,1200
Tablet,350
Printer,150
Keyboard,100

Step 3: Specify the path where the new CSV file will be saved

Now, specify the path where the new CSV file will be saved. For example:

C:\Users\Ron\Desktop\Test\New_Products.csv

Step 4: Convert the text file to CSV using Python

Finally, use the template below in order to facilitate the conversion of your text file to CSV:

import pandas as pd

read_file = pd.read_csv(r"Path where the Text file is stored\File name.txt")
read_file.to_csv(r"Path where the CSV will be saved\File name.csv", index=False)

For our example (note that you’ll need to modify the paths to reflect the location where the files are stored on your computer):

import pandas as pd

read_file = pd.read_csv(r"C:\Users\Ron\Desktop\Test\Product_List.txt")
read_file.to_csv(r"C:\Users\Ron\Desktop\Test\New_Products.csv", index=False)

Once you run the code in Python (adjusted to your paths), you’ll get the CSV file at your specified location.