Convert Text File to CSV using Python Pandas
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 CSV
Consider 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:

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.
Handling Text Files Without Headers
If 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:

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:

Handling Custom Delimiters
Some 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:

Depending 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.