1

我是 python 新手,我无法使用该del函数从列表中删除一些元素。我向它传递了一个包含多行的简单文本文件,使用创建行列表,splitlines()然后尝试使用del.

但是,当我运行它时,它只会打印出列表,而不会删除该行。但是,我可以使用del inputfile[:]. 它不会引发任何错误,我有点卡住了。

class Zero_Check(object):

    def __init__(self):
        self.path2file='C:\File2check\Output.txt'        

    def Parser(self):
        print('parser')

        inputfile = open(self.path2file).read().splitlines()
        del inputfile[4]
        print(inputfile)

        #for line in inputfile:
         #   print(line)

if __name__=='__main__':

    check=Zero_Check().Parser()

驱动器 C 中的卷是 OSDisk 卷序列号是 F0A9-9FB7

C:\File2check 目录

2015 年 8 月 10 日 16:36。

2015 年 8 月 10 日 16:36 ..

2015 年 8 月 10 日 16:28 0 1.txt

2015 年 8 月 10 日 16:28 0 10.txt

2015 年 8 月 10 日 16:28 0 11.txt

2015 年 8 月 10 日 16:31 2,411,884 12.txt

2015 年 8 月 10 日 16:31 2,411,884 13.txt

2015 年 8 月 10 日 16:31 2,411,884 14.txt

2015 年 8 月 10 日 16:31 2,411,884 15.txt

...

输出 -

[' Volume in drive C is OSDisk', ' Volume Serial Number is F0A9-9FB7', '', ' Directory of C:\\File2check', '08/10/2015  16:36    <DIR>          .', '08/10/2015  16:36    <DIR>          ..', '08/10/2015  16:28                 0 1.txt', '08/10/2015  16:28                 0 10.txt', '08/10/2015  16:28                 0 11.txt', '08/10/2015  16:31         2,411,884 12.txt', '08/10/2015  16:31         2,411,884 13.txt', '08/10/2015  16:31         2,411,884 14.txt', '08/10/2015  16:31         2,411,884 15.txt', '08/10/2015  16:31         2,411,884 16.txt', '08/10/2015  16:31         2,411,884 17.txt', '08/10/2015  16:33         1,457,843 18.txt', '08/10/2015  16:31         2,411,884 19.txt', '08/10/2015  16:28                 0 2.txt', '08/10/2015  16:31         2,411,884 20.txt', '08/10/2015  16:31         2,411,884 21.txt', '08/10/2015  16:33         1,457,843 22.txt', '08/10/2015  16:33         1,457,843 23.txt', '08/10/2015  16:33         1,457,843 24.txt', '08/10/2015  16:28                 0 3.txt', '08/10/2015  16:28                 0 4.txt', '08/10/2015  16:28                 0 5.txt', '08/10/2015  16:28                 0 6.txt', '08/10/2015  16:28                 0 7.txt', '08/10/2015  16:28                 0 8.txt', '08/10/2015  16:28                 0 9].txt', '08/10/2015  16:36                 0 Output.txt', '              25 File(s)     27,538,328 bytes', '               2 Dir(s)  593,421,463,552 bytes free']
4

1 回答 1

1

无需为简单操作制作类

def delete():
    with open('C:\File2check\Output.txt') as f:
        lines = f.readlines()
        print(lines)
        del lines[4]
        print(lines)
于 2015-10-08T17:27:56.890 回答