How to read text files with Python Pandas?

Learn, how can we read text files with Python Pandas? By Pranit Sharma Last updated : September 20, 2023

Pandas is a special tool which allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structure in pandas. DataFrames consists of rows, columns and the data. DataFrame can be created with the help of Python dictionaries or lists but in real world, csv files are imported and then converted into DataFrames.

Problem statement

Given a text file, we have to read it with Python Pandas.

Reading text files with Python Pandas

Pandas also support text files, and reading a text file is as similar as reading a csv file. The Pandas.read_csv() is used to read the text file and the actual path of the file with .txt format will be passed inside the method. Also encoding='utf-8' will be passed to prevent from the unicodeescape error.

Let us understand with the help of an example,

Python program to read text file with Python Pandas

# Import pandas package
import pandas as pd

# Reading a text file
data = pd.read_csv('D:/wrestlers.txt', encoding='utf-8')

# Creating a DataFrame
df = pd.DataFrame(data)

# Display DataFrame
print("Created DataFrame:\n",data)


The output of the above program is:

Example: Read text files with Pandas

Python Pandas Programs »

Comments and Discussions!

Copyright © 2023 All rights reserved.