Search code examples
pythonlistfiletext

Python Print each line of text file into list without \n


I'm still new to learning python and was just wondering how to store each line of a text file into a list without the \n appearing. I've tried:

file = open("test_file.txt", "r")
table = [line.split(') for line in file.readlines()]

Outputs:

[['Beans', ' 1222', ' 422', ' 6712\n'], ['Eggs', ' 4423', ' 122', ' 2231\n'], ['Tomato', ' 2232', ' 224', ' 2321']]

Desired output:

[['Beans', '1222', '422', '6712], ['Eggs', '4223', '122', '2231'], ['Tomato', '2232', '224', '2321']]

I've tried temp = file.read().splitlines() but it ends up storing it all into one list['Beans, 1222, 422, 6712', 'Eggs, 4423, 122, 2231', 'Tomato, 2232, 224, 2321'] when I still want each line to be a list itself. Any help greatly appreciated!!


Solution

  • In my case, I always use following line to get rid of \n every time I read a file:

    file = [line.strip("\n") for line in file.readlines()]
    

    In your case, just use:

    file = open("test_file.txt", "r")
    table = [line.strip("\n").split(') for line in file.readlines()]