Tutorials

Convert Text File (TXT) to CSV Using Python 3 Pandas Script

This tutorial will teach you how to convert a Text (.txt) file to CSV using the pandas library in Python. I’ll give you the complete source code of this application so you could easily test it out on your PC.

Let’s get started by installing the pandas library using the pip command.

pip install pandas

Now create a new Python file for this project and name it as code.py. After that, copy the below-given code-snippet and paste it in code.py.

code.py

# importing pandas library
import pandas as pd

# reading given csv from .txt file
# and creating dataframe
dataframe = pd.read_csv("file.txt", delimiter = ',')
  
# storing this dataframe in a csv file
dataframe.to_csv('new_file.csv', index = None)

According to our code, we need to provide a file.txt that contains our data. By default, commas will be used as delimiters, but you can easily change them to whatever character you like.

So, let’s create a file.txt in the root folder of your project and add some comma-separated values. For example, have a look at this file.

file.txt

ID, Name, Score
1, Furqan, 100
2, Ibrar, 95
3, Ammar, 87
4, Sheraz, 90
5, Babur, 65

Run Python Convert TXT to CSV Project

python code.py

The Output of Python TXT to CSV

A file named new_file.csv will be generated automatically in your project’s root folder.

Here’s a screenshot of that file:

Furqan

Well. I've been working for the past three years as a web designer and developer. I have successfully created websites for small to medium sized companies as part of my freelance career. During that time I've also completed my bachelor's in Information Technology.

Recent Posts

How can IT Professionals use ChatGPT?

If you're reading this, you must have heard the buzz about ChatGPT and its incredible…

September 2, 2023

ChatGPT in Cybersecurity: The Ultimate Guide

How to Use ChatGPT in Cybersecurity If you're a cybersecurity geek, you've probably heard about…

September 1, 2023

Add Cryptocurrency Price Widget in WordPress Website

Introduction In the dynamic world of cryptocurrencies, staying informed about the latest market trends is…

August 30, 2023

Best Addons for The Events Calendar Elementor Integration

The Events Calendar Widgets for Elementor has become easiest solution for managing events on WordPress…

August 30, 2023

Create Vertical Timeline in Elementor: A Step-by-step Guide

Introduction The "Story Timeline" is a versatile plugin that offers an innovative way to present…

August 30, 2023

TranslatePress Addon for Automate Page Translation in WordPress

Introduction In today's globalized world, catering to diverse audiences is very important. However, the process…

August 30, 2023