在python中读取和删除行

2024-04-24 22:01:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图读取一个特定文件中的所有行,它将该行的编号作为索引打印出来。你知道吗

我想做的是通过用户输入行号来删除行。 就目前而言,它打印所有带有该行编号的行,但是当我输入要删除的行的编号时,它不会被删除。你知道吗

这是删除函数的代码:

def deleteorders ():

    index = 0
    fh = open ('orders.txt', 'r')
    lines = fh.readlines()

    for line in lines:
        lines = fh.readlines()
        index = index+1
        print (str(index) + ' ' + line)


    try:
        indexinp = int(input('Enter the number of the order to be deleted, or "B" to go back: '))

        if indexinp == 'B':
            return
        else:
            del line[indexinp]
            print (line)

            fh = open ('orders.txt', 'w')
            fh.writelines(line)
            fh.close()

    except:
        print ('The entered number is not in the range')
        return

Tags: thetointxtnumberindexlineopen
1条回答
网友
1楼 · 发布于 2024-04-24 22:01:30

这应该可以工作(您需要将错误处理添加回):

lines = enumerate(open('orders.txt'))
for i, line in lines:
    print i, line
i = int(input(">"))
open('orders.txt', 'w').write(''.join((v for k, v in lines if k != i)))

相关问题 更多 >