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

Time:06-09

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!!

CodePudding user response:

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()]

CodePudding user response:

There's two quick solutions.

Since Yihua Zhou already provided one, I'll provide another. Please note that that the strip method might remove more than you want. Look at the docs for string.strip() here.

The splitlines() method splits a text on \n characters

with open("somefile.txt") as infile:
    table = [line.split() for line in infile.read().splitlines()]

Also note that if possible, you should use the with open() way to open files, as it closes it automagically. See this for some explanation...

CodePudding user response:

It appears that your input file is in fact a CSV file where the spaces after commas are to be ignored, in which case you can use csv.reader with the skipinitialspace option for better readability:

import csv

with open("test_file.txt") as file:
    table = list(csv.reader(file, skipinitialspace=True))

Demo: https://replit.com/@blhsing/TechnicalPlumpMathematics

  • Related