Home > Enterprise >  Write data in file using python
Write data in file using python

Time:05-21

I'm working on a python project and I want to write some data in a file text.txt but I have this error : UnboundLocalError: local variable 'data' referenced before assignment This is my code :

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/', methods=['POST','GET'])
def createapp():
    if request.method == 'POST':
        data = request.json
        print(data)
        
    with open('text.txt', 'a') as file:
        file.write(data)


if __name__ =='__main__':
    app.run()

CodePudding user response:

if request.method == 'POST':
    data = request.json
    print(data)
    
with open('text.txt', 'a') as file:
    file.write(data)

And what if request.method != 'POST'? You won't have defined data.


If you want to add something new (maybe a 0 or a []) when data is null, you may want to add this before the if statement:

data = None

CodePudding user response:

Set data to empty string before the condition. Otherwise it's undefined if the condition is false

data=''
if request.method == 'POST':
    data = request.json
    print(data)
    
with open('text.txt', 'a') as file:
    file.write(data)
  • Related