Read the following file formats using Pandas.
Read text files.
In the current working directory, first create a text file with the following text and saved with the name CarsInfo.txt.
Program
fo = open("CarsInfo.txt","r")
carsInfo = fo.read()
fo.close()
print("Cars Information:")
print(carsInfo)
carsInfo = fo.read()
fo.close()
print("Cars Information:")
print(carsInfo)
Output
Cars Information:
name showroomprice onroadprice
tata 6.32 8.02
benz 12.50 16.80
bmw 24.60 29.60
tata 10.60 14.80
name showroomprice onroadprice
tata 6.32 8.02
benz 12.50 16.80
bmw 24.60 29.60
tata 10.60 14.80
Read CSV Files
In the current working directory, first create a CSV file with the following details and saved with the name CarsInfo.csv.
Program
import pandas as pd
csv = pd.read_csv("CarsInfo.csv")
print("Cars Information:")
print(csv)
csv = pd.read_csv("CarsInfo.csv")
print("Cars Information:")
print(csv)
Output
Cars Information:
Name Show Room Price On-Road Price
0 tata 6.32 8.02
1 benz 12.50 16.80
2 bmw 24.60 29.60
3 tata 10.60 14.80
Name Show Room Price On-Road Price
0 tata 6.32 8.02
1 benz 12.50 16.80
2 bmw 24.60 29.60
3 tata 10.60 14.80
Read Excel Files
In the current working directory, first create a excel file with the following details and saved with the name CarsInfo.xlsx and also sheet name as CarPrices.
Program
import pandas as pd
with pd.ExcelFile("CarsInfo.xlsx") as excel:
carsInfo = pd.read_excel(excel,"CarPrices")
print("Cars Information:")
print(carsInfo)
with pd.ExcelFile("CarsInfo.xlsx") as excel:
carsInfo = pd.read_excel(excel,"CarPrices")
print("Cars Information:")
print(carsInfo)
Output
Cars Information:
Name Show Room Price On-Road Price
0 tata 6.32 8.02
1 benz 12.50 16.80
2 bmw 24.60 29.60
3 tata 10.60 14.80
Name Show Room Price On-Road Price
0 tata 6.32 8.02
1 benz 12.50 16.80
2 bmw 24.60 29.60
3 tata 10.60 14.80
Read JSON Files
In the current working directory, first create a JSON file as follows shown below and saved with the name CarsInfo.json.
Program
import json
with open("CarsInfo.json") as fo:
jsonData = json.load(fo)
print("Cars Information:")
print(jsonData)
with open("CarsInfo.json") as fo:
jsonData = json.load(fo)
print("Cars Information:")
print(jsonData)
Output
Cars Information:
{'name': ['benz', 'bmw', 'tata'], 'showroomprice': [12.5, 24.6, 10.6], 'onroadprice': [16.8, 29.6, 14.8]}
{'name': ['benz', 'bmw', 'tata'], 'showroomprice': [12.5, 24.6, 10.6], 'onroadprice': [16.8, 29.6, 14.8]}