Search code examples
pythonsys

Reading Multiple file in Python


I am learning python and in as much as the learning process seems to be going on smoothly. I am practically stuck trying to open a set of files all with the same structure using sys.argv. I have the following code that I cant understand how to fix it in order to perform similar operations on all the files.

import sys
if __name__ =='__main__':
    year_name = sys.argv[1]
    filename = open('year_2011.txt','r').readlines()
    for line in filename:
       line=line.strip('\t') # *seperated by tabs*
        year,y,x, amt # *columns in each of the filenames*
        y = int(y)
        x = int(x)
        amt = float(amt)

each time I run the simple code I get the error "list index out of range" any help on how I can solve this will be greatly appreciated


Solution

  • Your first line under the for loop wasn't properly indented. Also you were using strip instead of split.

    import sys
    if __name__ =='__main__':
        year_name = sys.argv[1]
        filename = open(year_name,'r').readlines()
        for line in filename:
            year, y, x, amt = line.split('\t') # *separated by tabs*
            y = int(y)
            x = int(x)
            amt = float(amt)