student
student

Reputation: 21

python writelines in one cell of csv

I have a quick question. I was trying to write a new csv file by reading another csv file, here is my code:

f_r = open("Bus.csv")
f_w = open("PJM_LMP.csv","w")
f = csv.reader(f_r)
for read_line in f:
    if read_line[3] == "PJM_H" or read_line[3] == "PJM_G":
        f_w.writelines(read_line)

f_r.close()
f_w.close()

it turns out that all the rows are written in on cell, I want to have them in different rows and cells, how may I change my code?

Upvotes: 0

Views: 119

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121186

Use a csv.writer() for the outputfile rather than try and write the list directly to the file:

with open("Bus.csv", 'rb') as f_r, open("PJM_LMP.csv", "wb") as f_w:
    reader = csv.reader(f_r)
    writer = csv.writer(f_w)
    writer.writerows(r for r in reader if r[3] in {"PJM_H", "PJM_G"})

The above code also uses the files as context managers, removing the need to call close() on them explicitly.

I've used a generator expression to filter what rows are written to the output file.

Upvotes: 2

Related Questions