简体   繁体   English

如何为CSV编写器编写python函数

[英]How to write a python function for csv writer

I have the following code that works fine: 我有下面的代码工作正常:

with open('userWithAgentProp.csv','w+') as f:
        w = csv.DictWriter(f,user_keys)
        w.writeheader()
        for user in userAgentProp_list:
            w.writerow(user)

I used this code to write a function: 我使用以下代码编写了一个函数:

def createCSVOutput(fileName, keys, listOfLists):
    with open(fileName, 'w+') as f:
        w= csv.dictWriter(f, keys)
        w.writeheader()
        for row in listOfLists:
            w.writerow(row)

When I call the function: 当我调用该函数时:

createCSVOutput('new_test_csv.csv', user_keys, userAgentProp_list)

I get the following error: 我收到以下错误:

File "mongodb_script_2.py", line 101, in <module>
  createCSVOutput('new_test_csv.csv', user_keys, userAgentProp_list)
File "mongodb_script_2.py", line 54, in createCSVOutput
  w= csv.dictWriter(f, keys)
AttributeError: 'module' object has no attribute 'dictWriter'

Why does it work for user_keys variable in the script, but not in the function? 为什么它对脚本中的user_keys变量有效,但对函数不起作用?

You have a typo: 您有错字:

csv.dictWriter is wrong. csv.dictWriter是错误的。 It should be csv.DictWriter . 它应该是csv.DictWriter

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

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