I'm trying to create a password generator that can delete lines consecutively off the password saver file. I've tried doing the same thing 4 times, but that doesn't work when trying to delete 4 lines after the 1st. Instead it deletes all the lines including that phrase of words. Here is some of my code:
with open("Password Saver.txt", "r+", encoding='utf-8') as file:
for line in file:
if line.find(reason) != -1:
for _ in range(4):
next(file)
else:
Things2Keep = Things2Keep + (line.rstrip())
f = open("Password Saver.txt", "w")
f.write(Things2Keep)
Try the following:
file.write("This is a placeholder.\n")
reason = "google"
with open("Password Saver.rtf",'rb') as IN:
lines = IN.readlines()
with open("Password Saver.rtf",'wb') as OUT:
for line in lines:
if line.lower().find(reason.lower()) != -1:
OUT.write(line)
Also, I think .rtf
files better be opened as binary.
So what I deduced from question and comments: remove the line that matches and four lines right after that.
header
google
1
2
3
4
footer
header
footer
Normally I would introduce a counter to be incremented on every line after the match, but for this answer I prefer to go a bit crazy and skip lines as file-like object is an iterator:
with open(fname, 'r', encoding='utf-8') as file:
for line in file:
if line.find(reason) != -1:
for _ in range(4):
next(file)
else:
print(line.rstrip())
This is only to demonstrate the principle, adapt it for file manipulation yourself, as an exercise =)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.