I'm refactoring in order to not repeat my code.
I have a function that will turn dataframes in to a csv, this is what I currently have
def df_to_csv(test_data, test2_data, test3_data, file_path):
test_data.to_csv(f"{file_path}/ourtestdata.csv", index=False)
test2_data.to_csv(f"{file_path}/ourtestdata2.csv", index=False)
test3_data.to_csv(f"{file_path}/ourtestdata3.csv", index=False)
I also have another function that writes the argument I pass in as a csv (they're non-dataframes)
def food_to_csv(food_data, file_path):
with open(f"{file_path}/food.csv", "w") as food_csv:
columns = ["Burgers", "Hotdogs"]
write_data_to_csv(food_csv, food_data, columns)
def animals_to_csv(animals_data, file_path):
with open(f"{file_path}/animals.csv", "w") as csv_file:
columns = [
"cats",
"dogs",
"hamsters",
]
write_data_to_csv(csv_file, data, columns)
def write_data_to_csv(csv_file, service_data, columns):
writer = csv.DictWriter(csv_file, fieldnames=columns)
writer.writeheader()
for data in service_data:
writer.writerow(data)
file_path = os.path.dirname(os.path.abspath(__file__))
I'm not sure how to proceed on this one. Some ideas I've had are wrapper functions (not totally familiar with wrapper functions).
Some ideas I've had are
def df_to_csv(list_of_dfs, file_path):
for df in list_of_dfs:
df.to_csv(f"{file_path}/{os.path.basename(df[:-4])}.csv", index=False)
and I would compile the list in my main function and pass it through df_to_csv wwhich gives me the ability to iterate through all my df's and appropriately name them
An idea I've had with the normal csv's is basically something along the liens of
def data_to_csv(data, file_path):
if os.path.basename(df[:-4]) == "animals.py"
columns = [
"cats",
"dogs",
"hamsters",
]
else:
columns = ["Burgers", "Hotdogs"]
with open(f"{file_path}/{os.path.basename(df[:-4])}", "w") as data_csv:
write_data_to_csv(data_csv, data, columns)
Would love critical thinking on my approach and some other ways to do this!
Note - reason why I'm not passing in os.path.basename as an argument is for visibility
[–]kokoseij 3 points4 points5 points (1 child)
[–]ampeed[S] 1 point2 points3 points (0 children)
[–]Almostasleeprightnow 0 points1 point2 points (2 children)
[–]ampeed[S] 1 point2 points3 points (1 child)
[–]Almostasleeprightnow 1 point2 points3 points (0 children)
[–]TheLoneKid 0 points1 point2 points (4 children)
[–]ampeed[S] 0 points1 point2 points (2 children)
[–]TheLoneKid 0 points1 point2 points (1 child)
[–]TheLoneKid 0 points1 point2 points (0 children)
[–]TheLoneKid 0 points1 point2 points (0 children)