
Please note, since we have specified that the input text file does not have column headers, our dataframe’s columns will not have any headers but plain indexes. Then we call read_csv() function with argument header=None to import text file into python dataframe. In the above code, we import Python pandas. # import pandas libraryĭf = pd.read_csv("data.txt", header = None) If your data file does not contain field headers, you need to specify header=None in read_csv() function. If your input data file data.txt looks like ID Name Marks The above code works when your text file’s 1st row contains column headers. Then we call to_csv() function to export it into CSV file data.csv. It returns a pandas dataframe stored in dataframe1. Then we use read_csv() file to read a text file data.txt. In the above code, we import Python pandas library. # import panda libraryĭataframe1.to_csv('data.csv', index = None)

In the first example, we import a text file and convert it into CSV file as it is. Let us look at a few examples to convert text file into CSV in python. How to Convert Text to CSV File in Python

Then we will call to_csv() function to export the dataframe as CSV file. This will create a dataframe with number of rows equal to number of lines in text file and number of columns equal to number of fields in text file.

Basically, we will import the text file to create a Pandas dataframe. In this article, we will learn how to convert text files to CSV files using Python pandas. In such cases, you may need to convert text files into CSV files to be able to use them with your scripts & applications. Sometimes you have received a text file whereas your applications accept only CSV files. Some applications work with Text files while some work with CSV files. Text files and CSV files are two most common file formats for exchanging information in today’s world.
