r/pythonhelp • • Jul 03 '22

How do I delete lines consecutively in a text file?

I have been trying to make a password saver for a generator, and I want to delete lines consecutively in the file. Here is some of my code:

if occ >= 1:rewrite = input("Would you like to rewrite the password for:"+ reason+ "?\n")if rewrite == "yes":f = open(reason, "a+")f.truncate(0)f.close()os.remove(f)shutil.move('C:/Python Practice/Password-Generator-30-01-22/'+reason, 'C:/Python Practice/Password-Generator-30-01-22/Password file folder and generator')`

3 Upvotes

5 comments sorted by

1

u/Goobyalus Jul 05 '22

I think this is what OP's code looks like formatted properly:

file.write("This is a placeholder.\n")

with open("Password Saver.rtf", "r+", encoding='utf-8') as file:
	for line in file:
		if line.find(reason) != -1:
			str(reason)
			for _ in range(4):
				next(file)
		else:
			Things2Keep = (line.rstrip())
f = open("Password Saver.rtf", "w")
f.write(Things2Keep)

str(reason)

doesn't do anything

Things2Keep = (line.rstrip())

will overwrite Things2Keep with a new string each time instead of appending to it

1

u/GeneralIrohLovesZuko Jul 07 '22

How can I make it append?

1

u/Goobyalus Jul 07 '22

If you're keeping it as a string, += ...

If you make it into a list and combine it at the end, which is better, .append(...)

1

u/PicoPlanetDev Jul 03 '22

I'm wondering if you could share more of the code or logic that it uses because I'm not sure just from this what the program is trying to accomplish.

Also, RTF is generally pretty cluttered. If possible I'd suggest switching to plaintext.

1

u/Goobyalus Jul 05 '22 edited Jul 05 '22

Alsonext(file) doesn't work here, the for loop has its own iterator over the file that isn't affected by your nexts.