Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function to save multiple csv files with different names in python?

I am trying to write a function in python that essentially splits the original CSV file into multiple csv files and saves their names. The code that I have written so far looks like this:

def split_data(a, b, name_of_the_file):
    part = df.loc[a:b-1]
    filename = str(name_of_the_file)
    part.to_csv(r'C:\path\to\file\filename.csv', index=False)

The main intention of the code is to name each file a different name, which is the input (name_of_the_file). The code seems to work, but only saves the file as filename.csv.

like image 659
self.novice_coder Avatar asked May 21 '26 11:05

self.novice_coder


1 Answers

Your function is saving the file(s) with the name filename.csv because you only specify that name in the following line:

part.to_csv(r'C:\path\to\file\filename.csv', index=False)

To change the name you need to change the string to take the filename variable:

part.to_csv(f'C:\path\to\file\{filename}.csv', index=False)

Notice how the string has a f in the beginning of it -- this is called an f-string and it allows you to add Python variables directly into the string by using curly brackets ({filename}).

like image 57
Felipe Avatar answered May 22 '26 23:05

Felipe