简体   繁体   中英

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 :)

In your for loop: for i in range(5): variable i is assigned values 0, 1,2,3,4; so when you try to access sys.argv[i+3] i+3 is 3,4,5,6,7, but you only have 4 elements in sys.argv .

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM