[英]Python: how to create a csv column based on a function's parameter
I have function that write to a csv file with a set of column.我有 function 写入带有一组列的 csv 文件。 Whenever I want to change some column, I have to go into my code and change it manually.每当我想更改某些列时,我必须将 go 放入我的代码并手动更改它。 How can I input the column name as a parameter and it will change the rest?如何输入列名作为参数,它会改变 rest?
My current code:我当前的代码:
def write_to_csv():
data_writer = csv.DictWriter(open('output.csv', 'w', encoding='utf-8', newline=''), fieldnames=['fund', 'Ticker', 'Price, 'Date'])
data_writer.writeheader()
for row in input_file:
data_writer.writerow({'fund': fund, 'Ticker': row[0].value, 'Price': row[1].value, 'Date': row[2].value)
So let say, instead of changing the column Ticker
to Name
manually, I would like to use a parameter in the function so that: if I need the column Ticker
, I would execute write_to_csv(Ticker)
.因此,可以说,我不想手动将Ticker
列更改为Name
,而是想在 function 中使用一个参数,这样:如果我需要Ticker
列,我将执行write_to_csv(Ticker)
。 If I need Name instead of ticker, I would execute write_to_csv(Name)
.如果我需要 Name 而不是 ticker,我会执行write_to_csv(Name)
。
I think the problem I am facing is to call the parameter in the quotes我认为我面临的问题是在引号中调用参数
It's actually simpler than you're thinking.它实际上比你想象的要简单。
def write_to_csv(column_variant='Ticker'):
# Use a with block so the file auto-closes
with open('output.csv', 'w', encoding='utf-8', newline='') as csv_file:
data_writer = csv.DictWriter(csv_file, fieldnames=['fund', column_variant, 'Price, 'Date'])
data_writer.writeheader()
for row in input_file:
data_writer.writerow({'fund': fund, column_variant: row[0].value, 'Price': row[1].value, 'Date': row[2].value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.