Loading Different Data Files in Python
We are given different Data files and our task is to load all of them using Python. In this article, we will discuss how to load different data files in Python.
Loading Different Data Files in Python
Below, are the example of Loading Different Data Files in Python:
- Loading Plain Text Files
- Loading Images
- Loading Excel Files
- Loading Audio Files
Loading Plain Text Files in Python
In this example, the below code shows how to load plain text files in Python. First, it opens the file in read mode ensures proper closing, and then reads the entire file content into a variable named ‘data‘.
example.txt
w3wiki is a Coding Platform
with open('example.txt', 'r') as f:
data = f.read()
print(data)
Output:
w3wiki is a Coding Platform
Loading Images in Python
In this example, below code loads and displays an image using OpenCV and Matplotlib. It first imports libraries and attempts to read the image “download3.png”. An ‘if statement’ checks for successful loading. If successful, Matplotlib displays the image with a large figure size and hidden axes.
import matplotlib.pyplot as plt
import cv2
try:
image = cv2.imread('download3.png')
if image is not None:
plt.figure(figsize=(18, 18))
plt.imshow(image)
plt.show()
else:
print("Error! Something went wrong!")
except Exception as e:
print("OOps! Error!", e)
Output:
Loading Excel Files in Python
In this example, below code loads a retail sales dataset from an Excel file. It defines the file path and imports the pandas library for data manipulation. The core functionality lies in data = pd.read_excel(file_path), which reads the Excel data into a pandas DataFrame named data.
excel.xlsx
import pandas as pd
file_path = 'excel.xlsx'
data = pd.read_excel(file_path)
print(data.head())
Output:
A B
0 12 13
1 14 15
2 16 17
Loading Audio Files in Python
In this example, below code uses librosa, a powerful library for audio analysis. It starts by loading an audio file and the loaded audio data is stored in ‘audio‘ (represented as a NumPy array), while ‘sampling_rate‘ captures the frequency at which the audio was recorded (samples per second).
import librosa
file_path = "Roa-Haru.mp3"
audio, sampling_rate = librosa.load(file_path)
# display data
print(f"Audio data: {audio.shape}")
print(f"Sampling rate: {sampling_rate} Hz")
Contact Us