简体   繁体   中英

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?

You have a typo:

csv.dictWriter is wrong. It should be csv.DictWriter .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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