Mark A
Mark A

Reputation: 61

reading a csv file and removing \n in Python

I'm trying to read a csv file and put the elements in an array but the last element of each row is being joined with the first element of the following row with a \n in the middle. Here is the code:

f = open("read_file.csv", "r+")
lines = f.read().split(',')


f.close()
print lines

exit()

Upvotes: 0

Views: 1199

Answers (2)

Vedu Joshi
Vedu Joshi

Reputation: 36

How about this ?

f = open("read_file.csv", "r+")
lines = f.readlines()
print sum([x.rstrip('\n').split(',') for x in lines],[])

Upvotes: 0

Lim H.
Lim H.

Reputation: 10050

You would want to use the csv module in the standard library

import csv
with open('read_file.csv', 'r+') as csvfile:
    lines = csv.reader(csvfile)
    for line in lines:
        # do your stuff here

Upvotes: 3

Related Questions