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 ‘/’.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.