Home > front end >  Loop over lines in file, create list from 2nd column
Loop over lines in file, create list from 2nd column

Time:11-05

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**

CodePudding user response:

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

CodePudding user response:

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.

  • Related