0

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)
Computing102
  • 25
  • 1
  • 5

4 Answers4

2

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"]]
asc11
  • 419
  • 3
  • 7
  • Thank you, how then would I differentiate between the lists should I wish to append to either one? – Computing102 Oct 03 '16 at 11:52
  • 1
    Isn't this answer doing exactly what the code in the question already does? – Efferalgan Oct 03 '16 at 11:54
  • 1
    @Computing102 simply use list indexes. If you want the list of names for say, line 5. Just say `for name in entires[5]:`. – Christian Dean Oct 03 '16 at 11:55
  • 1
    @Computing102: `entries` is only one list, that happens to be made of two other lists. You can access its elements like with any other list: `entries[0]` will return `["John", "Doe"]` and `entries[1]` will return `["John", "Smith"]`. – Efferalgan Oct 03 '16 at 11:57
  • @Computing102 if this answer solved, or _helped_ solved your problem, then consider accepting it. – Christian Dean Oct 03 '16 at 13:10
0

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

JMat
  • 752
  • 6
  • 14
0

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()]
Howardyan
  • 667
  • 1
  • 6
  • 15
0

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

gl051
  • 571
  • 4
  • 8