Home > front end >  How can I add a path to the CSV files created?
How can I add a path to the CSV files created?

Time:05-13

Im splitting a CSV file based on column "ColumnName". How can I make all the CSV files created save into a specified path?

  data = pd.read_csv(r'C:\Users\...\Output.csv')
  for (ColumnName), group in data.groupby(['ColumnName']):
       group.to_csv('{ColumnName}.csv', index=False)

Thanks

CodePudding user response:

pandas.DataFrame.to_csv() takes a string path as input to write to said path.

With your current code group.to_csv('{ColumnName}.csv', index=False), {ColumnName} is being interpreted as a normal string. If you wanted variable substition in this case Python has many methods, two would be:

f-strings - Introduced in Python 3.6

group.to_csv('{ColumnName}.csv', index=False)

str.format

group.to_csv('{}.csv'.format(ColumnName), index=False)


Specifying path

Following this. If you're looking to specify more than just the file name, you are able to specify the full file path or the file path relative to the current directory.

Providing full file path

Full file paths require describing the path from the root context. In windows this would be providing a path such as f'C:\Users\mycsvfolder\{ColumnName}.csv'. Providing the full path to to_csv() will have the file written there.

Note In linux, root context starts at /. So for example /Users/myuser/mycsvfolder/file.csv would be the full file path.

Providing a relative file path

Relative file paths take into account the current folder. For example, to instead write to a folder within the current folder you are able to specify f'mycsvfolder/{ColumnName}.csv' and the file will be written to the specified folder in the current directory. It's with this method that writing f'{ColumnName}.csv' will write a file, but to the current directory as work is relative to the current directory unless otherwise specified.

Note when writing to folder

You will need to create folders before writing to them in most cases. Some write functions do provide folder creation functionality however.

Additional material regarding paths, specifically in Python.

  • Related