如何读取CSV并将每一行改编为另一CSV?

时间:2019-04-05 12:32:01

标签: python csv

我尝试过此操作,但是它只是多次写入“ 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])

它看起来应该像this

1 个答案:

答案 0 :(得分:0)

这是在输出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:)编写以上代码。答案here显示了如何处理多个文件(在本例中为fInfOut)。