[英]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.我还是 Python 新手,我想创建一个可以根据命令行参数读/写/附加文本文件的程序。
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 IndexError:列表索引超出范围
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;在你的 for 循环中:
for i in range(5):
变量i
被赋值为 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
.因此,当您尝试访问
sys.argv[i+3]
i+3
是 3,4,5,6,7,但您在sys.argv
只有 4 个元素。
If you call your program with如果你调用你的程序
python3 program.py textfile.txt w word1 word2
you will have a total of 5 command line arguments.您将总共有 5 个命令行参数。 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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.