[英]Python 2.7.10 csv how to write each version of an iterating output in a new row
I want to write an iterating output, with each version in a new row of the csv. 我想编写一个迭代输出,每个版本都放在csv的新行中。 I have tried this:
我已经试过了:
#matching questions
for ind1,key1 in enumerate(file1):
for ind2,key2 in enumerate(file2):
ques1 = file1[key1]
ques2 = file2[key2]
match_ratio = difflib.SequenceMatcher (None, ques1, ques2).ratio()
n = csv.writer(open("output.csv", "wb"))
n.writerow([key1, ques1, key2, ques2, match_ratio])
As you can see I am trying to match two strings each from a different dictionary and then I want to output the key and value of each and the match ratio into a csv file so I can work with the output in excel. 如您所见,我试图匹配来自不同词典的两个字符串,然后将每个字符串的键和值以及匹配率输出到一个csv文件中,以便可以在excel中使用输出。 However, only the last versions of each variable is getting output and I have no clue why.
但是,只有每个变量的最新版本都可以输出,我也不知道为什么。
Why is it not outputting the variables into a new row in the csv each time? 为什么每次都不将变量输出到csv中的新行中? What should I do to make this happen?
我应该怎么做才能做到这一点?
Thanks in advance! 提前致谢!
您的代码将在每次迭代时重写数据,而是以追加模式打开文件。
As @amal-ts said, you should use append mode to open file. 正如@ amal-ts所说,您应该使用附加模式打开文件。
And opening file in every loop is bad idea, so you should consider using with
在每个循环中打开文件是个坏主意,因此您应该考虑使用
with
with open("output.csv", "ab") as f:
for ind1,key1 in enumerate(file1):
for ind2,key2 in enumerate(file2):
ques1 = file1[key1]
ques2 = file2[key2]
match_ratio = difflib.SequenceMatcher (None, ques1, ques2).ratio()
n = csv.writer(f)
n.writerow([key1, ques1, key2, ques2, match_ratio])
Finally, you should check match_ratio
value to check your blank row problem. 最后,您应该检查
match_ratio
值以检查您的空白行问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.