Dec-10-2019, 02:00 PM
I want to delete a block of text from a text file that looks like this:
But I only want to delete 1 block of text that starts with
So I have this code:
I want this one gone from the text file:
This is the part from the whole code that should do it:
Thank you.
Quote:1
Date stored: 2019-02-01;
Author name: l;
Book title: lll;
Quantity: 1;
Price: 2.
2
Date stored: 2019-01-02;
Author name: ghjk;
Book title: okj;
Quantity: 5;
Price: 4.
4
Date stored: 2019-01-02;
Author name: hello;
Book title: hekie;
Quantity: 1;
Price: 2.
1
Date stored: 2019-02-01;
Author name: k;
Book title: k;
Quantity: 4;
Price: 1.
1
Date stored: 2019-01-01;
Author name: o;
Book title: b;
Quantity: 4;
Price: 8.
5
Date stored: 2019-02-01;
Author name: dfgh;
Book title: iuhg;
Quantity: 8;
Price: 4.
But I only want to delete 1 block of text that starts with
1So I have this code:
from itertools import groupby
mainFileDelete = open("BooksTest.txt","r+")
lst = []
new = []
for line in mainFileDelete:
stripped = line.strip("\n")
lst.append(stripped)
#Makes a list into a list of lists
def splitList(sequence, delimiter):
return [list(g) for k, g in groupby(sequence, key = lambda x: x == delimiter) if not k]
p = splitList(sequence = lst, delimiter = '')
print(p)
#Gets the sublists that starts with a number '1'
for k in p:
this=k
if this[0] == '1':
new.append(this)
print(new)
#Trys to make all of the list of lists into a string an then delete it from
#the text file
for i in new:
strinng = ''.join(i)
print(strinng)
for a in strinng:
if a != strinng[1]:
f.write(a)
f.truncate()
mainFileDelete.close()It gives me all of the the blocks of text that start with 1 in a list of lists, like so:[['1', 'Date stored: 2019-02-01; ', 'Author name: l; ', 'Book title: lll; ', 'Quantity: 1; ', 'Price: 2. '], ['1', 'Date stored: 2019-02-01; ', 'Author name: k; ', 'Book title: k; ', 'Quantity: 4; ', 'Price: 1. '], ['1', 'Date stored: 2019-01-01; ', 'Author name: o; ', 'Book title: b; ', 'Quantity: 4; ', 'Price: 8.']]And I want to delete just the second list from the list of lists. I know how to do it from the actual list. But I don't know how could I also delete it from the file.
I want this one gone from the text file:
Quote:1
Date stored: 2019-02-01;
Author name: k;
Book title: k;
Quantity: 4;
Price: 1.
This is the part from the whole code that should do it:
#Trys to make all of the list of lists into a string an then delete it from
#the text file
for i in new:
strinng = ''.join(i)
print(strinng)
for a in strinng:
if a != strinng[1]:
f.write(a)
f.truncate()But it doesn't work at all. Please help. It's the only thing I can't seem to figure out. Thank you.
