VOOZH about

URL: https://www.geeksforgeeks.org/python/convert-text-file-to-csv-using-python-pandas/

⇱ Convert Text File to CSV using Python Pandas - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert Text File to CSV using Python Pandas

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

👁 Image
Original Text File

Output:

👁 Image
CSV File formed from given text file

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:

👁 Image
Text File without headers

Output:

👁 Image
CSV file with headers

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

Output:

👁 Image
CSV File

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.

Comment
Article Tags:
Article Tags: