I want to write an iterating output, with each version in a new row of the csv. I have tried this:
我想编写一个迭代输出,每个版本都在csv的新行中。我试过这个:
#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. However, only the last versions of each variable is getting output and I have no clue why.
正如您所看到的,我正在尝试匹配来自不同字典的两个字符串,然后我想将每个字符串和值以及匹配率输出到csv文件中,以便我可以使用excel中的输出。但是,只有每个变量的最后版本得到输出,我不知道为什么。
Why is it not outputting the variables into a new row in the csv each time? What should I do to make this happen?
为什么每次都没有将变量输出到csv中的新行?我该怎么做才能实现这一目标?
Thanks in advance!
提前致谢!
2 个解决方案
#1
0
As @amal-ts said, you should use append mode to open file.
正如@ amal-ts所说,你应该使用append模式来打开文件。
And opening file in every loop is bad idea, so you should consider using 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值以检查空行问题。
#2
0
Your code is rewriting the data on each iteration, instead open the file in append mode.
您的代码在每次迭代时重写数据,而是以追加模式打开文件。
#1
0
As @amal-ts said, you should use append mode to open file.
正如@ amal-ts所说,你应该使用append模式来打开文件。
And opening file in every loop is bad idea, so you should consider using 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值以检查空行问题。
#2
0
Your code is rewriting the data on each iteration, instead open the file in append mode.
您的代码在每次迭代时重写数据,而是以追加模式打开文件。