0

This code that i've done sometimes deletes the entire file, can someone tell me what's the problem and solve it?

from flask import Flask
from flask.globals import request



app = Flask(__name__)

@app.route('/claim/<code>')
def index(code):
  with open('codes.txt') as file:
    for i in file:
      if i.strip() == str(code):
       with open('codes.txt', 'w') as newfile:
         for x in file:
           if x != str(code):
             newfile.write(x)
         return "VALID"
  return "INVALID"

if __name__ == "__main__":
  app.run(debug=True)```
  • 3
    so much of redundant code...`opening & for ,if ` can be done once instead of doing thme twice – Ajay Apr 03 '21 at 09:19
  • When you open the file for writing, you erase its previous contents. You'll need to read all the lines into memory before you open the file for writing. But this seems extremely inefficient; probably switch to using SQLite instead, which offers simple, transparent ability to remove one record without the need to rewrite all the others. – tripleee Apr 03 '21 at 09:40

0 Answers0