0

I tried this but it just writes "lagerungskissen kleinkind,44" several times instead of transferring every row.

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

Zahra
  • 6,798
  • 9
  • 51
  • 76
zimon
  • 77
  • 6

1 Answers1

0

This is writing the same line in your output CSV because the final block is

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

Note that the keyword variable doesn't change in the loop, but the row does. You're writing that same [keyword, rank] line len(keyword) times.

I would use the csv package to do the reading and the writing for this. 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 (e.g. with open(...) as file:). The answer here shows how to do it with multiple files (in this case fIn and fOut).

Andrew F
  • 2,690
  • 1
  • 14
  • 25