简体   繁体   English

如何读取CSV并将每行调整+写入另一个CSV?

[英]How to read a CSV and adapt + write every row to another CSV?

I tried this but it just writes "lagerungskissen kleinkind,44" several times instead of transferring every row. 我尝试了这个,但它只是写了几次“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])

It should look like this 它看起来应该是这样的

This is writing the same line in your output CSV because the final block is 这是在输出CSV中写入相同的行,因为最后一个块是

for row in keyword:
    thewriter.writerow([keyword, rank])

Note that the keyword variable doesn't change in the loop, but the row does. 请注意, keyword变量在循环中不会更改,但row会更改。 You're writing that same [keyword, rank] line len(keyword) times. 你写的是相同的[keyword, rank]len(keyword)次。

I would use the csv package to do the reading and the writing for this. 我会使用csv包来完成阅读和写作。 Something like 就像是

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()

As as side note, you could write the above using the with context manager (eg with open(...) as file: ). 如旁注所示,您可以使用with context manager编写上述内容(例如with open(...) as file: The answer here shows how to do it with multiple files (in this case fIn and fOut ). 这里的答案显示了如何使用多个文件(在本例中为fInfOut )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM