Search code examples
pythondel

del function not working in python


I am new to python and I am having trouble deleting some elements from a list using the del function. I am passing it a simple text file with several lines, creating a list of the lines using splitlines() and then trying to delete the first few elements of the by using del.

When I run it however it just prints out the list without the line deleted. I can however delete everything using del inputfile[:]. It throws no errors and I am a little stuck.

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()

Volume in drive C is OSDisk Volume Serial Number is F0A9-9FB7

Directory of C:\File2check

08/10/2015 16:36 .

08/10/2015 16:36 ..

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

...

output -

[' 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']

Solution

  • No need to make a class for simple operation

    def delete():
        with open('C:\File2check\Output.txt') as f:
            lines = f.readlines()
            print(lines)
            del lines[4]
            print(lines)