Dynamically save output csv to match name of input csv python

Question:

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).

Asked By: Loz

||

Answers:

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")
Answered By: Chandler Kenworthy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.