user1546610
user1546610

Reputation: 185

Start reading and writing on specific line on CSV with Python

I have a CSV file that looks like this:

COL_A,COL_B
12345,A=1$B=2$C=3$

How do I read that file and wrote it back to a new file but just the second row (line)? I want the output file to contain:

12345,A=1$B=2$C=3$

Thanks!

Upvotes: 0

Views: 5291

Answers (2)

Lanaru
Lanaru

Reputation: 9721

The following reads your csv, extracts the second row, then writes that second row to another file.

with open('file.csv') as file:
    second_line = list(file)[1]

with open('out.csv', mode = 'w') as file:
    file.write(second_line)

Upvotes: 3

Joran Beasley
Joran Beasley

Reputation: 114038

outfile = open(outfilename,"w")
with open(filename) as f:
    for line in f:
       print >> outfile , line.split()[-1]
outfile.close()

as long as the lines actually look like the line you posted in the OP

Upvotes: 0

Related Questions