Last Updated : 15 Mar, 2025
Converting Text File to CSV using Python Pandas refers to the process of transforming a plain text file (often with data separated by spaces, tabs, or other delimiters) into a structured CSV (Comma Separated Values) file using the Python Pandas library.
In this article we will walk you through multiple methods to convert a text file into a CSV file using Python's Pandas library.
Convert a Simple Text File to CSVConsider a text file named GeeksforGeeks.txt
containing structured data. Python will read this data and create a DataFrame where each row corresponds to a line in the text file and each column represents a field in a single line.
import pandas as pd
df1 = pd.read_csv("GeeksforGeeks.txt")
df1.to_csv('GeeksforGeeks.csv',
index = None)
Output:
CSV File formed from given text fileThe 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.
Handling Text Files Without HeadersIf the column heading are not given and the text file looks like. In this case you need to manually define the column headers while converting to CSV:
Text File without headers Python
import pandas as pd
websites = pd.read_csv("GeeksforGeeks.txt"
,header = None)
websites.columns = ['Name', 'Type', 'Website']
websites.to_csv('GeeksforGeeks.csv',
index = None)
Output:
CSV file with headers Handling Custom DelimitersSome text files use custom delimiters instead of commas. Suppose the file uses /
as a separator. To handle this specify the delimiter while reading the file
import pandas as pd
account = pd.read_csv("GeeksforGeeks.txt",
delimiter = '/')
account.to_csv('GeeksforGeeks.csv',
index = None)
Output:
CSV FileDepending on the structure of the text file you may need to specify headers or handle custom delimiters. With these methods you can easily transform text-based data into a structured format for further analysis.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4