Home > Software design >  Dynamically save output csv to match name of input csv python
Dynamically save output csv to match name of input csv python

Time:12-21

I have a dataframe:

cat input.csv
dwelling,wall,weather,occ,height,temp
5,2,Ldn,Pen,154.7,23.4
5,4,Ldn,Pen,172.4,28.7
3,4,Ldn,Pen,183.5,21.2
3,4,Ldn,Pen,190.2,30.3

Which I import using:

input_df = pd.read_csv('input.csv')

Do some calculations to, and then export as a .csv, using:

input_df.to_csv('Results/input_results.csv')

I would like to export the .csv so that it is always named the same as the input file, but with "_results.csv" added without having to manually do it each time (preferably with pandas but open to other ways).

CodePudding user response:

Just set up a variable with the name of the input file and use a f-string.

inFile = "input"
df = pd.read_csv(f"{inFile}.csv")
...
df.to_csv(f"Results/{inFile}_results.csv")
  • Related