Reading Text File in Python

Reading data into an analytical tool is one of the first steps before proceeding to analytics. Some of the common challenges while reading a text file are

  • Knowing Delimiter
  • Presence of Missing  or null values
  • Column values holding date values

In this blog, we will read text file in which values are separated by a tab (reading a tab delimited file).  Here is the sample of the file.

Tab Delimited

Python Code for Reading Tab Delimited File

# Read Text File in Python
cust_t ="C:\Python\Training\data\cust_tab.txt"
file = open(cust_t, "r")
lines ="\n")

# define length of columns
ID = ["" for x in range(len(lines))]
Gender = ["" for x in range(len(lines))]
Age = ["" for x in range(len(lines))]

for l in lines:
    values = l.split("\t")
# Create Data frame
import pandas as pd
df ={ 'ID':ID,
      'Age' : Age   
df= pd.DataFrame(df)

Output Data Frame

Tab Delimited Output Data Frame

Same Python code above will work even if input Text file has Missing values.

Accessing Column(s) of Data Frame in Python

If we want to access single or multiple columns of the input Data Frame, we can use below Python code.

#Access Single Column
# Access multiple Columns

Access Columns

Leave a Comment