Jul-10-2022, 05:36 AM
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
I'm not sure how to write the condition for deleting the A/B/C/D option together with the question entered by user.
Here is my code:
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
I'm not sure how to write the condition for deleting the A/B/C/D option together with the question entered by user.
Here is my code:
import os
def main():
import os
answer = input("Enter question to delete:")
with open("testing.txt", "r") as read:
with open("temp.txt", "w") as output:
# iterate all lines from file
for line in read:
# if text matches then don't write it
if line.strip("\n") != answer:
output.write(line)
read.close()
output.close()
# replace file with original name
os.replace('temp.txt', 'testing.txt')
main()
