Let’s see how to Convert Text File to CSV using Python Pandas. Python will read data from a text file and will create a dataframe with rows equal to number of lines present in the text file and columns equal to the number of fields present in a single line. See below example for better understanding.
Dataframe created from upper text file will look as follows:
Note: The first column in dataframe is indexing which is by default when a text file is read.
Once the dataframe is created, we will store this dataframe into a CSV file format using Dataframe.to_csv() Method.
Let’s see examples:
The text file read is same as above. After successful run of above code, a file named “GeeksforGeeks.csv” will be created in the same directory.
Example 2: Suppose the column heading are not given and the text file looks like:
Then while writing the code you can specify headers.
We see that headers have been added successfully and file has been converted from ‘.txt’ format to ‘.csv’ format.
Example 3: In this example, the fields in the text file are separated by user defined delimiter “/”.
While reading data we specify that data should be tokenized using specified delimiter. In this case ‘/’.
- Create a GUI to convert CSV file into excel file using Python
- Python program to read CSV without CSV module
- Saving Text, JSON, and CSV to a File in Python
- How to Convert an image to NumPy array and saveit to CSV file using Python?
- How to skip rows while reading csv file using Pandas?
- Pandas - DataFrame to CSV file using tab separator
- Convert CSV to Excel using Pandas in Python
- Convert Text and Text File to PDF using Python
- Convert HTML table into CSV file in python
- Different ways to import csv file in Pandas
- How to read a CSV file to a Dataframe with custom delimiter in Pandas?
- How to export Pandas DataFrame to a CSV file?
- Export Pandas dataframe to a CSV file
- Convert a NumPy array into a csv file
- Python | Read csv using pandas.read_csv()
- Convert CSV to JSON using Python
- How to save a Python Dictionary to a CSV File?
- Replacing column value of a CSV file in Python
- Using csv module to read the data in Pandas
- Convert JSON to CSV in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.