【问题标题】:How to delete a word in each line of a text file, error message [duplicate]如何删除文本文件每一行中的一个单词,错误消息[重复]
【发布时间】: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


    【解决方案1】:

    您的输入文件中可能有一个尾随换行符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多