pythonlistcsv

Remove new line \n reading from CSV


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'],

Solution

  • simply call str.strip on each line as you process them:

    score = []
    
    for eachLine in file:
        student = eachLine.strip().split(',')
        score.append(student)
    
    print(score)