In the data world, when working with Python, it is often
necessary to read CSV or Excel files using a function. To accomplish this, a
dynamic method can be implemented, which will take the input file and check its
file extension type, such as csv, xls, or xlsx.
The purpose of this dynamic method is to determine the
file type and then appropriately read the file and process the data. This
approach allows for flexibility in handling different file formats, ensuring
that the data can be efficiently retrieved and utilized.
This scenario is a commonly encountered problem in
real-time projects that involve handling and analyzing data. By implementing a
dynamic method to read and process different file types, it becomes easier and
more efficient to work with varied data sources, ultimately enhancing
productivity and data extraction capabilities.
Step1 : Import Librearies
import csv
import sys
import pandas as pd
Step 2 read csv: This method
will read CSV file
def read_csv(file):
try:
df=pd.read_csv(file)
print(df)
except FileNotFoundError:
print("File
not found")
except Exception as err:
print("An
Exception error",err)
Step 3: This method will read
XLS/XLSX file
def read_xls(file):
try:
df=pd.read_excel(file,sheet_name='data')
print(df)
except FileNotFoundError:
print("File
not found")
except Exception as err:
print("An
Exception error",err)
Step 4: Enter your input file
def file_process(filename):
if filename.endswith(".csv"):
read_csv(filename)
elif filename.endswith('.xls') or
filename.endswith('.xlsx'):
read_xls(filename)
else:
print("Unsupported file
type")
filename=r'G:\ETL_Automation\data\datasingle.xlsx'
file_process(filename)
0 Comments
Thanks for your message.