Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[['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()]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading