Python Forum

Full Version: Delete multiple lines from txt file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Does anyone know how to delete lines in txt file according to user input without using any list or dictionary?

For example content inside txt file:
Question 1 Which is correct?
A. X
B. XX
C. XXX
D. XXXX
Question 2 Which is wrong?
A. X
B. XX
C. XXX
D. XXXX
Question 3 Which is True?
A. X
B. XX
C. XXX
D. XXXX

When user choose to delete question 2, the file will updated and the output will become like this:
Question 1 Which is correct?
A. X
B. XX
C. XXX
D. XXXX
Question 3 Which is True?
A. X
B. XX
C. XXX
D. XXXX
The best way to do this is:
  1. Copy the lines of the original file to a temporary file, but don't copy the lines you do not want.
  2. If no errors occurred: remove the original file.
  3. Rename the temporary file to the name of the original file.
def remove_lines_list (file):
    ip_list = open(file).readlines()
    return [address.rstrip('\n') for address in ip_list]
I use this function to take a list of IP addresses and remove all the trailing \n so i get a clean list with no extra spaces or lines.. i dont know if this is helpful but i use this when getting a txt file in put of IP addresses i need to loop through.
(Jul-09-2022, 06:00 PM)ibreeden Wrote: [ -> ]The best way to do this is:
  1. Copy the lines of the original file to a temporary file, but don't copy the lines you do not want.
  2. If no errors occurred: remove the original file.
  3. Rename the temporary file to the name of the original file.
What will be the condition for A. B. C. D.?
(Jul-10-2022, 12:09 AM)jcrubaugh45 Wrote: [ -> ]
def remove_lines_list (file):
    ip_list = open(file).readlines()
    return [address.rstrip('\n') for address in ip_list]
I use this function to take a list of IP addresses and remove all the trailing \n so i get a clean list with no extra spaces or lines.. i dont know if this is helpful but i use this when getting a txt file in put of IP addresses i need to loop through.
It can't work as I need to delete the whole question not only one line.
(Jul-10-2022, 05:32 AM)Lky Wrote: [ -> ]What will be the condition for A. B. C. D.?
Introduce a boolean variable e.g. "do_copy". If this variabel is true, copy the line. Else not.
When a line contains: "Question 2 " then toggle the variable to False.
When a line contains: "Question" then toggle the variable to True.
That should work, as long as Question does not appear in any answers. Basically using a flag that is unique to the category of line Question.
Suggest also - do this in memory, with option of displaying output, then do the write after approval. Skips the swap part, or you can allow user to Save As with a different filename. Adds a little versatility