Computing102
Computing102

Reputation: 25

Python: Reading text file and splitting into different lists

I have a text file which contains two lines of text. Each line contains student names separated by a comma.

I'm trying to write a program which will read each line and convert it to a list. My solution seems to make two lists but I don't know how to differentiate between the two as both lists are called "filelist". For example I may need to append to the second list. How would I differentiate between the two?

Or is it possible for it to create completely separate lists with different names? I want the program to be able to handle many lines in the text file ideally.

My code is:

    filelist=[]

    with open("students.txt") as students:

            for line in students:

                    filelist.append(line.strip().split(","))


    print(filelist)

Upvotes: 0

Views: 4000

Answers (4)

gl051
gl051

Reputation: 571

If you are looking to have a list for each line, you can use a dictionary where the key is the line number and the value of the dictionary entry is the list of names for that line. Something like this

with open('my_file.txt', 'r') as fin:
    students = {k:line[:-1].split(',') for k,line in enumerate(fin)}

print students

The line[:-1] is to get rid off the carriage return at the end of each line

Upvotes: 0

Howardyan
Howardyan

Reputation: 657

two lines to done

with open("file.txt") as f:
    qlist = map(lambda x:x.strip().split(","), f.readlines())

or

with open("file.txt") as f:
    qlist = [i.strip().split(",") for i in f.readlines()]

Upvotes: 0

JMat
JMat

Reputation: 737

in your code, filelist will be considered as a list of list because you append a list to it, not an element, consider doing filelist += line.strip().split(",") which will concatenate the lists

Upvotes: 0

asc11
asc11

Reputation: 449

You will have to create a multi-dimensional array like this:

text = open("file.txt")

lines = text.split("\n")
entries = []
for line in lines:
    entries.append(line.split(","))

If your file is

John,Doe
John,Smith

then entries will be:

[["John", "Doe"], ["John", "Smith"]]

Upvotes: 2

Related Questions