I'm using a function which takes 3 .csv files as input to process the data in the files. The function is as follows:
def pull_data(sheet1,sheet2,sheet3, usn_number):
# Open the first sheet
with open(sheet1, 'r') as sheet1_file:
sheet1_reader = csv.reader(sheet1_file)
# Open the second sheet
with open(sheet2, 'r') as sheet2_file:
sheet2_reader = csv.reader(sheet2_file)
# Open the third sheet
with open(sheet3, 'r') as sheet3_file:
sheet3_reader = csv.reader(sheet3_file)
with open(f'{group}.csv', 'w') as csv_file:
csv_writer = csv.writer(csv_file)
writer = csv.DictWriter(csv_file, fieldnames=["USN","Subject Code","Student_Name","Classes Attended","Total Classes","Attendance_Percentage"])
writer.writeheader()
for row in sheet1_reader:
# Check if the usn number is in the first sheet
if usn_number in row:
# If it is, add the row to the csv file
row.insert(1, sheet1.replace(".csv",""))
csv_writer.writerow(row)
# Loop through the second sheet
for row in sheet2_reader:
# Check if the usn number is in the second sheet
if usn_number in row:
# If it is, add the row to the csv file
row.insert(1, sheet2.replace(".csv",""))
csv_writer.writerow(row)
for row in sheet3_reader:
# Check if the usn number is in the second sheet
if usn_number in row:
# If it is, add the row to the csv file
row.insert(1, sheet3.replace(".csv",""))
csv_writer.writerow(row)
for usn in groups:
pull_data('18MAT41.csv','18CS42.csv','18CS43.csv', usn)
How to take dynamic number of file input? like in place of 3 files i want to take n number of files dynamically.
CodePudding user response:
In python you create variadic arguments by prepending:
*
(usually*args
), to put the remaining positional arguments in a tuple**
(usually**kwargs
), to put the remaining keyword arguments in a dict
The function definition must look like
def func(arg1, arg2, *args, kwarg1=1, kwarg2=2, **kwargs):
For a very simple example:
def concat_strings(*s):
return "".join(s)
concat_strings("a", "b", "c") # gives "abc"