【发布时间】:2021-03-01 18:53:35
【问题描述】:
我编写了一个程序来删除每行中的第一个单词。该代码工作正常,但一旦读取结果,它就会向我抛出一条错误消息。 我不明白为什么,它应该工作。我不知道如何解决这个错误,你能帮帮我吗?
demofile.txt
>=3 1 2 3
>=2 4 5 6
>=1 1 2 4 4
代码
#remove first word in each line from demofile
f = open("demofile.txt", "r")
lines = f.readlines()
with open('output.txt', mode='w', newline='\n') as output:
for i in list(lines):
# remove operators and first number from demofile
sfn = i.split(" ", 1)
#print(sfn)
newfilename = sfn[1]
output.write(newfilename)
结果
1 2 3
4 5 6
1 2 4 4
Traceback (most recent call last):
File "C:\Users\Pifko\dp\skuska.py", line 20, in <module>
newfilename = sfn[1]
IndexError: list index out of range
【问题讨论】:
标签: python text-files