How to read an excel, csv, json file in Python
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Python is a versatile programming language that can be used for a wide range of tasks, including data analysis and manipulation.
One common task that many people need to do is reading data from external files, such as Excel, CSV, and JSON files.
In this article, we will go over how to read these types of files in Python using built-in libraries.
First, let's start with reading an Excel file.
The most popular library for working with Excel files in Python is pandas.
To read an Excel file, you will first need to install the pandas library by running "pip install pandas" in your terminal.
Once you have pandas installed, you can use the read_excel() function to read an Excel file. Here is an example of how to do this:
import pandas as pd
# Read the Excel file
data = pd.read_excel('file.xlsx')
# Print the first 5 rows
print(data.head())
In this example, we are importing the pandas library and using the read_excel() function to read the data from the "file.xlsx" Excel file. We then use the head() function to print the first 5 rows of the data.
Next, let's look at reading a CSV file. The built-in csv library in Python can be used to read CSV files. Here is an example of how to do this:
import csv
# Open the CSV file
with open('file.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
# Print the contents of the CSV file
for line in csv_reader:
print(line)
In this example, we are importing the csv library and using the open() function to open the "file.csv" CSV file. We then use the csv.reader() function to create a CSV reader object, which we can use to iterate through the lines of the CSV file. We then use a for loop to print the contents of the CSV file.
Finally, let's look at reading a JSON file. The json library in Python can be used to read JSON files. Here is an example of how to do this:
import json
# Open the JSON file
with open('file.json', 'r') as json_file:
data = json.load(json_file)
# Print the contents of the JSON file
print(data)
In this example, we are importing the json library and using the open() function to open the "file.json" JSON file. We then use the json.load() function to load the data from the JSON file into a Python object. We then use the print() function to print the contents of the JSON file.
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚