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.
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}).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With