Bruh Lol Bruh Lol - 7 months ago 11
Python Question

Appending a document line by line to a list

I am trying to get each word in the text document "Payments" into a list. For each line of "Payments", I want it within a list in

myList
, so it would look something like this:

myList = [['E1234','12/09/14','440','A','0']['E3431','10/01/12','320','N','120']['E0987','04/12/16','342','A','137']]


I need to use
.split()
and
.strip()
in order to remove individual words from the commas and to remove the invisible next line space at the end of every line. This is my code that I have written so far:

myFile = open("Payments.txt")
myList = []
for line in myFile:
print(line.strip())
myList.append(line.strip())
myFile.close()
print(myList)


The program does work, but not in the way I was intending it to work. The program returned the following:

E1234,12/09/14,440,A,0
E3431,10/01/12,320,N,120
E0987,04/12/16,342,A,137
E5322,05/04/02,503,A,320
E9422,26/11/16,124,N,0
E7382,31/03/11,414,A,235
['E1234,12/09/14,440,A,0', 'E3431,10/01/12,320,N,120', 'E0987,04/12/16,342,A,137', 'E5322,05/04/02,503,A,320', 'E9422,26/11/16,124,N,0', 'E7382,31/03/11,414,A,235']


It has appended the document into
myList
, but it hasn't put each line into its' own list within
myList
and the line is a whole string, not individual strings, separated by a comma.

I did try adding
.split(',')
at the end of
for line in myFile:
, but it displayed an error message:

AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

Answer

You need to call .split() on each line:

myList = []
for line in myFile:
    print(line.strip())
    myList.append(line.strip().split(","))

Or, in one line using a list comprehension:

myList = [line.strip().split(",") for line in myFile]

Or, you can also use a csv module:

import csv

with open("Payments.txt") as f:
    reader = csv.reader(f)
    myList = list(reader)

print(myList)