How to read text files with Python Pandas?

Learn, how can we read text files with Python Pandas?
Submitted by Pranit Sharma, on May 23, 2022

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.

Pandas also support text files, and reading a text file is as similar as reading a csv file. 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,

# 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)


Example: Read text files with Pandas

Python Pandas Programs »


What's New (MCQs)

Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.