Reputation: 97
I have a CSV file which looks like:
Name1,1,2,3
Name2,1,2,3
Name3,1,2,3
I need to read it into a 2D list line by line. The code I have written almost does the job; however, I am having problems removing the new line characters '\n'
at the end of the third index.
score=[]
for eachLine in file:
student = eachLine.split(',')
score.append(student)
print(score)
The output currently looks like:
[['name1', '1', '2', '3\n'], ['name2', '1', '2', '3\n'],
I need it to look like:
[['name1', '1', '2', '3'], ['name2', '1', '2', '3'],
Upvotes: 3
Views: 12103
Reputation: 21446
You can use splitlines
First method
>>> s = '''Name1,1,2,3
... Name2,1,2,3
... Name3,1,2,3'''
>>> [ item.split(',') for item in s.splitlines() ]
[['Name1', '1', '2', '3'], ['Name2', '1', '2', '3'], ['Name3', '1', '2', '3']]
Second method
>>> l = []
>>> for item in s.splitlines():
... l.append(item.split(','))
...
>>> l
[['Name1', '1', '2', '3'], ['Name2', '1', '2', '3'], ['Name3', '1', '2', '3']]
Upvotes: 1
Reputation: 302
Use the rstrip function to identify \n at the end of every line and remove it. See the code below for reference.
with open('myfile.csv', 'wb') as file:
for line in file:
line.rstrip('\n')
file.write(line)
Upvotes: 0
Reputation: 2753
If you know it's a \n, and a \n only,
score=[]
for eachLine in file:
student = eachLine[:-1].split(',')
score.append(student)
print(score)
Uses slicing to remove the trailing new line characters before the split happens.
EDITED, per the suggestions of the commentors ;) Much more neat.
Upvotes: 0