Loop over lines in file, create list from 2nd column

Question:

I’m trying to loop over the lines in an output file I created that looks like this:

2020-03-19, 22.0
2020-03-20, 6.0
2020-03-21, 5.0

And then create and print a list with the numbers in the 2nd column.

This is just my main and the function I’m having trouble with:

def main(): 
    for file in FILE_PATH_INPUT:
        fWriteOutputFile(file)
    print(fReadOutputFile(FILE_PATH_OUTPUT))
```


def fReadInputFile(pFile):
    casesList = []
    with open(pFile, 'r') as fi:
        lines = fi.readlines()
        for line in lines:
            line = line.rstrip().split(',')
            casesList.append(str(line[1]))
    return casesList
        

```


**What I'm expecting:
[66, 6, 5]
what I'm getting:
casesList.append(str(line[1]))
IndexError: list index out of range**

Asked By: nina

||

Answers:

If you just want to print the list, you don’t need manually add "," to each element. Instead, you can write fReadOutputFile in the following way:

def fReadOutputFile(pFile):
    casesList = []
    with open(pFile, 'r') as fi:
        lines = fi.readlines()
        for line in lines:
            line = line.rstrip().split(',')
            casesList.append(str(line[1]))
    return casesList
Answered By: Chen Lin

The problem is in this section of code:

        line = line.rstrip().split(',')
        caseslist = str(line[1]) + ','
        casesList.append(caseslist)

In the second line, ‘line’ still contain text (it’s a string) , You have to convert to integer.
Correct way is:

        line = line.rstrip().split(',')
        casesList.append( int( line[1])

Also, the "file.close()" is located after the ‘return’. So the ‘close’ will never be executed.

Answered By: user3435121
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.