beatfloraminederecho
beatfloraminederecho

Reputation: 231

Write data in file using python

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

Upvotes: 0

Views: 88

Answers (2)

FLAK-ZOSO
FLAK-ZOSO

Reputation: 4088

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 = ''

Upvotes: 3

Mohammad Rifat Arefin
Mohammad Rifat Arefin

Reputation: 427

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)

Upvotes: 2

Related Questions