[英]Loop ending after one iteration. Python
I am attempting to read a csv file of multiple rows, each delimited like this: quote|source|dob-dod|wplink|wpimg|category我正在尝试读取多行的 csv 文件,每行都这样分隔:quote|source|dob-dod|wplink|wpimg|category
I want to check for rows that contain the category string 'romantic' and output that to a JSON.我想检查包含类别字符串“浪漫”的行并将其输出到 JSON。 I think I am nearly there but my loop stops after finding the first row with the relevant string.
我想我快到了,但是在找到具有相关字符串的第一行后,我的循环停止了。 What am I missing to keep the loop going to find all relevant rows?
我缺少什么来保持循环查找所有相关行? Your help is very much appreciated!
非常感激你的帮助! Here is my code so far:
到目前为止,这是我的代码:
import csv,json
#create an empty dictionary
romantic = {}
with open('quotes.csv') as csvfile:
data = csv.reader(csvfile, delimiter = '|')
#filter using str: romantic
for row in data:
if row[5] == 'romantic':
romantic['quotes'] = {
'quote': row[0],
'source': row[1],
'dob-dod': row[2],
'wplink' : row[3],
'wpimg': row[4],
'category':row[5]
}
with open('romjson', 'w+') as jsonfile:
jsonfile.write(json.dumps(romantic))
#print the json
print(romantic)
You have an issue that you rewrite romantic['quotes']
every time you get if row[5] == 'romantic':
condition, try this code instead (I've used list to store all quotes)你有一个问题,你每次得到
if row[5] == 'romantic':
条件时,你重写romantic['quotes']
,试试这个代码(我用 list 来存储所有引号)
import csv,json
#create an empty dictionary
romantic = {'quotes': []}
with open('quotes.csv') as csvfile:
data = csv.reader(csvfile, delimiter = '|')
#filter using str: romantic
for row in data:
if row[5] == 'romantic':
romantic['quotes'].append({
'quote': row[0],
'source': row[1],
'dob-dod': row[2],
'wplink' : row[3],
'wpimg': row[4],
'category':row[5]
})
with open('romjson', 'w+') as jsonfile:
jsonfile.write(json.dumps(romantic))
#print the json
print(romantic)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.