Trying to read information in a file into two lists in Python
Question: I think this is a relatively simple question but i'm a beginner and having
trouble. I have to read in information from a text file into two lists in
python.

This is an example of what the text file looks like, it is called
'ratings.txt' and the three colums are movieId|numberofRatings|averageRatings.

    
    
    1|452|3.9
    2|131|3.2
    3|90|3
    4|209|3.6
    ...
    ...
    1321|2|2.5
    ...
    ...
    1685|0|-nan
    1686|0|-nan
    

I need to read in the second and third columns of numbers into two separate
arrays. the second column of numbers needs to be read into a list numRatings.
and the third column needs to be read into a list avgRatings. the text file
goes from movies 1 to 1686

so `numRatings` needs to be `[452,131,90,....0,0]` and `avgRating` needs to be
`[3.9,3.2,3,....-nan,-nan]`

I think I have to create the lists, and then create loops to read through the
text file and store these numbers in the array.

here is my code so far

    
    
    f = open("ratings.txt") #opens the text file
    line = f.readline() #reads in one line of the file
    a = line.split("|") #splits the line of the file, for example line 1 looks like [1, 452, 3.9]
    

in the above code if I print `a[0]`, `a[1]` and `a[2]` I get `1`, `452`, and
`3.9` respectively.

How do I do this over and over again and store my results into the arrays?


Answer: You really have a CSV-style file, so use the [`csv`
module](http://docs.python.org/2/library/csv.html):

    
    
    import csv
    
    results = []
    with open('ratings.txt', 'rb') as f:
        reader = csv.reader(f, delimiter='|')
        for row in reader:
            results.append(row)
    

You could augment this as needed; append the second and third columns to
separate lists, converting them to `int`s and `float()`s, for example:

    
    
    numRatings = []
    avgRating = []
    with open('ratings.txt', 'rb') as f:
        reader = csv.reader(f, delimiter='|')
        for row in reader:
            numRatings.append(int(row[1]))
            avgRating.append(float(row[2]))
    

If this _were not_ a CSV-style file, you'd still use a loop; you'd loop
directly over the file object:

    
    
    with open('ratings.txt', 'rb') as f:
        for line in f:
            a = line.strip().split("|")
    

