2017-02-28 1588 views
0

我試圖創建一個從字典一個CSV創建CSV文件,但我收到的錯誤:類型錯誤:參數1必須有一個「寫」的方法 - 從字典

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

代碼:

#Create dict file to test 
userInfoDict = {'orgID': '17', 'firstName': 'TestFirstName', 'lastName': 'TesLastName', 
       'emailAddress': '[email protected]', '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) 

回答

3

你應該通過你的文件,但沒有文件名的作家:

with open('userInfo.csv', 'wb') as userInfoCsv: 
    writer = csv.writer(userInfoCsv) 
  • 你不應該有'。'符號在你的變量的名稱,所以你的變量應該是userInfoCsvuser_info_csv

  • userInfo = open('userInfo.csv', 'wb')爲什麼你用這條線?你打開以後使用with open('userInfo.csv', 'wb')

  • 你的文件,你可以看到一個方法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 全功能與評論

    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) 
    
    +0

    更改代碼以匹配更新代碼你的修復,它似乎沒有任何影響。同樣的錯誤。在create_csv writer = csv.writer('userInfocsv') TypeError:參數1必須有一個「寫入」方法 – Eric

    +0

    當然,open應該發生在循環之前。因爲它是每個循環將再次打開文件並覆蓋以前的內容。 – Matthias

    +0

    @Matthias當然,所以沒有意義使用語句 –

    相關問題