[英]AttributeError: 'NoneType' object has no attribute 'encode' while writing into file?
[英]AttributeError: 'NoneType' object has no attribute 'get' when writing into a file
我正在嘗試從網站上抓取(對不同用戶使用循環),然后將其保存在字典中並將其寫入文件中。
問題是用戶數以百計,並不是每個用戶在 json 中都有相同的數據。 對於沒有特定數據行的用戶,它給了我這個錯誤。
for i in range(10):
u = User(list_of_users[i])
try:
data_list = [[u.name, u.full_name, u.date_of_birth
,u.current_age, p.job_info.get('UserId').get('JobId'), p.job_info_with_z.get('UserId').get('location')]]
except AttributeError:
data_list = [[u.name, u.full_name, u.date_of_birth
,u.current_age, p.job_info.get('UserId').get('JobId'), p.job_info_with_z.get('UserId').get('location')]]
with open('test_players_data.csv', 'a', newline='') as file:
writer = csv.writer(file, delimiter=',')
writer.writerows(data_list)
.name 調用一個方法來獲取名稱,就像 job_info 和 info_with_z 一樣。
所以這適用於大多數用戶,但對於沒有“UserId”的用戶,它會給我上述錯誤。 但是有些用戶會有 UserId 但沒有 UserIdWithZ。 我想跳過具有一些默認值的那些並繼續抓取數據並將其寫入文件中。 一旦失敗,它就不會向前 go 前進。
必須有一種方法可以在不存在鍵的情況下提供默認值。 我已經修剪了數據。 所以每個用戶都有超過 30 個不同的值,我試圖在 4 個代碼塊中抓取它們。
示例數據
{
'UserId': {'jobId': '74', 'jobLocation': '72', 'jobType': '10'},
'UserIdWithZ: {'jobId': '74', 'jobLocation': '72', 'jobType': '10'}
}
我只希望在.csv 中的行/記錄填充沒有任何數據而不僅僅是失敗的“”或“-”或“na”。
提前致謝
在您的情況下使用.get
指定默認值,
p.job_info.get('UserId', {}).get('JobId', '-')
如果您希望dict
鏈接下一個get
您需要將默認值指定為{}
。 如果job_info.get('UserId')
沒有值,則None
將是默認值,它沒有get
方法。
對所有.get
方法執行相同操作,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.