0

i have a csv file from where in i read the data and store individual coloumns in list , but for the last coloumn i am getting \n in the list . i want to get rid of that .

f = open('datagen.txt')
  for lines in f:
      line = lines.split(',')
      l1.append(line[0])
      l2.append(line[1])

l2 contains like abcd\n in it .. i dont want the newline character .

4
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by pyTony
0

You can replace line 3 with line = lines.rstrip().split(',')

Note that this will probably cause an error at
l2.append(line[1])
because length will be too short. You should be testing for length anyway:

f = open('datagen.txt')
for lines in f:
    line = lines.strip().split(',')
    if len(line) > 1:
        l1.append(line[0])
        l2.append(line[1])

Edited by woooee: n/a

0

Also your indention is of (maybe only copy paste error). And it is good practice to learn to use with statement which automatically will close the file for you after processing and also if there is error in file handling in the block.

Here is shown how to get easier the columns by reading lines and transposing by zip(*lines).

with open('datagen.txt') as f:
    lines = [ line.strip().split(',') for line in f]

columns = zip(*lines)
print columns[0]
print columns[1]
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.