Steps to Convert Text File to CSV using Python
Step 1: Install the panda's package
If you haven’t already done so, install the panda's package. You may use the following command to install the panda's package under Windows:
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.
For example, I stored a text file (called Product_List) under the following path: C:\Users\Ron\Desktop\Test
Step 3:
Finally, you may 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=None)
For our example:
- The path where the Text file is stored is: C:\Users\Ron\Desktop\Test\Product_List.txt
- Where the file name is Product_List and the file extension is txt
- The path where the CSV will be saved is C:\Users\Ron\Desktop\Test\New_Products.csv
- Where the new file name to be created is New_Products and the file extension is CSV
So this is the complete code to convert the Text file to CSV for our example:
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=None)
Once you run the code (adjusted to your paths), you’ll get the CSV file at your specified location: