0

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()

2 Answers 2

3
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 = ''
Sign up to request clarification or add additional context in comments.

2 Comments

I'm new to python I just want to add those data in the file text.txt
Small correction - data = '', otherwise TypeError will be raised
2

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)

7 Comments

Actually you will raise a TypeError here, because you must write a string to file. data = '' will fix it
thank you but the data is null I want to write in my file the data = request.json
You can write into the file within the if block. In that case, you don't need to declare data beforehand.
If I write it inside the if block it didn't show in the text.txt
So you are saying data is printed on terminal but not written into the text.txt file? Check what's printed on terminal.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.