简体   繁体   English

动态保存输出 csv 以匹配输入 csv python 的名称

[英]Dynamically save output csv to match name of input csv python

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:做一些计算,然后导出为 a.csv,使用:

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).我想导出 the.csv,以便它始终与输入文件同名,但添加了“_results.csv”,而不必每次都手动执行(最好使用 pandas,但可以通过其他方式打开)。

Just set up a variable with the name of the input file and use a f-string.只需使用输入文件的名称设置一个变量并使用 f 字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM