Reading a text file in python

read_write
python

#1

What would be the command to read a text file in Python. Also if the text file has a dataframe built in it, would it be read as a dataframe only? If not, how can I convert it into a dataframe.


#2

you can read the file line by line as list of list, based upon the structure of file.

list_of_lists = []

with open(‘filename.txt’) as f:
for line in f:
inner_list = [line.strip() for line in line.split(’ split character’)]
list_of_lists.append(inner_list)

** split character = inspect txt file how columns are separated, normally tab.

once you have list of list you can convert it to dataframe using pandas.
df = pd.Dataframe(list_of_lists)


#3

Hi @himanshu.doi

A text file can be read through python inbuilt libraries as

import csv

f = open("myfile.txt", 'r')
reader = csv.reader(f) 

Now if you file is arranged in a tabular format, you should use pandas library. Most of the times you would prefer using pandas library, as it has more holistic functions commonly used in data science. You would read the file in pandas as

import pandas as pd
df = pd.read_csv('myfile.txt')

Now just to clarify, dataframe is a data structure defined by pandas library. It is not an inbuilt data structure of python. When you read a file using pandas, it is normally stored in dataframe format.

Hope it clears your doubt.