Search code examples
pythonpython-2.7python-3.xargvsys

fileku.write(sys.argv[i+3]+'\n') IndexError: list index out of range


i'm still new in python,i want to create a program that can read/write/append text file depending on the command line argument.

here is my code :

import sys

def prosesfile():
        fileku=open(sys.argv[1],sys.argv[2])
        if(sys.argv[2] == 'w'):
                for i in range(5):
                        fileku.write(sys.argv[i+3]+'\n')
                print('proses tulis file selesai.')
        elif(sys.argv[2] == 'r'):
                for i in fileku:
                        print(i)
                print('proses baca selesai.')
        elif(sys.argv[2] == 'a'):
                for i in range(5):
                        fileku.write(sys.argv[i+3]+'\n')
                print('proses append file selesai.')

prosesfile()

then i tried to execute:

python3 program.py textfile.txt w word1 word2

but then i got an error :

File "program.py", line 14, in prosesfile
fileku.write(sys.argv[i+3]+'\n')

IndexError: list index out of range

What happen? is there anything wrong with my code? thanks :)


Solution

  • If you call your program with

    python3 program.py textfile.txt w word1 word2
    

    you will have a total of 5 command line arguments. The loop:

    for i in range(5):
        fileku.write(sys.argv[i+3]+'\n')
    

    will try to access elements beyond that.

    Change to this:

    for arg in sys.argv[3:]:
        fileku.write(arg+'\n')