我试过这个,但它只是多次写入“lagerungskissen kleinkind,44”,而不是传输每一行。
keyword = []
rank = []
rank = list(map(int, rank))
data = []
with open("keywords.csv", "r") as file:
for line in file:
data = line.strip().replace('"', '').split(",")
keyword = data[0]
rank = data[3]
import csv
with open("mynew.csv", "w", newline="") as f:
thewriter = csv.writer(f)
thewriter.writerow(["Keyword", "Rank"])
for row in keyword:
thewriter.writerow([keyword, rank])
它应该是这样的
这是在输出 CSV 中写入同一行,因为最后一个块是
for row in keyword:
thewriter.writerow([keyword, rank])
请注意,keyword
变量在循环中不会改变,但row
会改变。你正在写同样的[keyword, rank]
行len(keyword)
时间。
我会用这个csv
包来做这个的阅读和写作。就像是
import csv
input_file = '../keywords.csv'
output_file = '../mynew.csv'
# open the files
fIn = open(input_file, 'r', newline='')
fOut = open(output_file, 'w')
csvIn = csv.reader(fIn, quotechar='"') # check the keyword args in the docs!
csvOut = csv.writer(fOut)
# write a header, then write each row one at a time
csvOut.writerow(['Keyword', 'Rank'])
for row in csvIn:
keyword = row[0]
rank = row[3]
csvOut.writerow([keyword, rank])
# and close the files
fOut.close()
fIn.close()
作为旁注,您可以使用with
上下文管理器(例如with open(...) as file:
)编写上述内容。此处的答案显示了如何处理多个文件(在本例中为fIn
和fOut
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句