Eric Eric -4 years ago 516
Python Question

TypeError: argument 1 must have a "write" method -- creating csv from dict

I'm trying to create a csv from a dict, but I'm receiving the error:

in create_csv
writer = csv.writer('userInfo.csv')
TypeError: argument 1 must have a "write" method


Code:

#Create dict file to test
userInfoDict = {'orgID': '17', 'firstName': 'TestFirstName', 'lastName': 'TesLastName',
'emailAddress': 'test@test.com', 'phoneNumber': '123-456-7890',
'isoCountryCode': 'US'}

def create_csv(userInfoDict):
import csv

userInfo = open('userInfo.csv', 'wb')

for key in userInfoDict:
if len(userInfoDict['orgID']) == 0:
print('Not a valid user: No orgID')
return None
elif len(userInfoDict['firstName']) == 0:
print('Not a valid user: No First Name')
return None
elif len(userInfoDict['emailAddress']) == 0 or len(userInfoDict['phoneNumber']) == 0:
print('Not a valid user: No Email or Phone')
return None
else:
writer = csv.writer(userInfo, delimiter=',')
for key, value in userInfoDict.items():
writer.writerow([key], [value])
return

create_csv(userInfoDict)

Answer Source

You should pass your file but not the file name to the writer:

with open('userInfo.csv', 'wb') as userInfoCsv:
    writer = csv.writer(userInfoCsv)
  1. You should not have the '.' symbol in the name of your variable, so you variable should be userInfoCsv or user_info_csv

  2. userInfo = open('userInfo.csv', 'wb') why you use this line? You open your file later using with open('userInfo.csv', 'wb')

  3. You could see a method csv.DictWriter

    with open('userInfo.csv', 'wb') as user_info_csv:
        writer = csv.DictWriter(user_info_csv, fieldnames=['your', 'column', 'names'], delimiter=';')
        writer.writerow(userInfoDict)
    

UPDATE full code of function with updates from comments

def create_csv(userInfoDict):
    import csv

    with open('userInfo.csv', 'wb') as userInfo:

        for key in userInfoDict:
            if len(userInfoDict['orgID']) == 0:
                print('Not a valid user: No orgID')
                return None
            elif len(userInfoDict['firstName']) == 0:
                print('Not a valid user: No First Name')
                return None
            elif len(userInfoDict['emailAddress']) == 0 or len(userInfoDict['phoneNumber']) == 0:
                print('Not a valid user: No Email or Phone')
                return None
            else:
                writer = csv.DictWriter(userInfo, fieldnames=userInfoDict.keys(), delimiter=';')
                # writer.writeheader()  # If you want to add header
                writer.writerow(userInfoDict)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download