Reputation: 161
I am creating pandas DataFrames in a for loop and I would like to save them in csv files with different names at each iteration of the for loop.
I know how to save one DataFrame:
path = r"C:\Users\SessionName\FolderName\FileName.csv"
df.to_csv(path)
Now when I have a list of strings, e.g.
countries = ['United States', 'China', 'Russia', 'India']
I would like the four files to be named United States_ranking.csv
, China_ranking.csv
, etc.
I have tried:
for country in countries:
path = r"C:\Users\SessionName\FolderName\" + country + "_ranking.csv"
But is won't work.
Upvotes: 0
Views: 3234
Reputation: 23099
personally, I would use pathlib
to handle your paths. also be careful for typos in your code.
for example,
import pandas as pd
from pathlib import Path
src_path = r"C:\Users\SessionName\FolderName\FileName.csv"
countries = ['United States', 'China', 'Russia', 'India']
for country in countries:
p = Path(src_path).parent.joinpath(f"{country}_ranking.csv")
df.to_csv(p,index=False)
this will write:
C:\Users\SessionName\FolderName\United States_ranking.csv
C:\Users\SessionName\FolderName\China_ranking.csv
C:\Users\SessionName\FolderName\Russia_ranking.csv
C:\Users\SessionName\FolderName\India_ranking.csv
The benefit of having a pathlib object here is that you can check if the directory is valid or if the file exists before hand.
print(p)
WindowsPath('C:/Users/SessionName/FolderName/United States_ranking.csv')
if not p.is_file():
df.to_csv(p,index=False)
else:
print('file exists')
Upvotes: 2
Reputation: 236
Looks like rawstring dont work with "\"
and the end of the string.
You can fix it by adding extra \ after your path to folder by puting double "\\"
in another string.
countries = ['United States', 'China', 'Russia', 'India']
for country in countries:
path = r"C:\Users\SessionName\FolderName" + "\\" + country + "_ranking.csv"
Upvotes: 0
Reputation: 989
use this:
for country in countries:
path = r"C:\\Users\\SessionName\\FolderName\\ {} _ranking.csv".format(country)
Upvotes: 2
Reputation: 152
I prefer os.path.join(folder, country+filename)
for country in countries:
path = os.path.join("C:\\Users\\SessionName\\FolderName\\", country + "_ranking.csv")
df.loc[df.country == country].to_csv(path)
Upvotes: 0
Reputation: 337
You have to write the path like this, otherwise it causes a problem with "\"
for country in countries:
path = r"C:\\Users\\SessionName\\FolderName\\" + country + "_ranking.csv"
Upvotes: 0