Moun
Moun

Reputation: 315

write in a file.txt in the flask server page

Here is the code i execute in a normal python script it works, but when it comes to a flask function he create the file.txt, but with no writing in it

app = Flask(__name__)
@app.route('/execute',methods=['POST'])

def execute():
    message = request.get_json(force=True)
    name=message['name']
    path="data/"
    testname="test.txt"
    encodedname="encoded.txt"

    output = open(path+testname, "wb")
    output.write(name.encode('utf-8'))

here the writing works for the first time

    with open(path+testname, 'rb') as infile:
        data = infile.readlines()
        all_data=""
        for oneline in data:
            oneline=oneline.decode('utf-8')
            print(

oneline)
            new_data = re.sub(r'[^\u0600-\u065F\u0670-\u06ef\u0750-\u077f\ufb50-\ufbc1\ufbd3-\ufd3f\ufd50-\ufd8f\ufd50-\ufd8f\ufe70-\ufefc\uFDF0-\uFDFD]+',' ', oneline)
            new_data = re.sub('[\ufd3e\ufd3f]',' ',new_data)
            new_data = remove_punctuations(new_data)
            new_data = new_data+'@\n'
            all_data = all_data+new_data
    cleanedtest = open(path+"cleanToTest.txt",'wb')
    cleanedtest.write(all_data.encode('utf-8'))

but here it doesn't (cleanedTest)

Upvotes: 0

Views: 37

Answers (1)

Sekizyo
Sekizyo

Reputation: 26

You should use context manager. Your issue is that you need to close this file after you write to it. Context manager will do it for you automatically.

Change this:

output = open(path+testname, "wb")
output.write(name.encode('utf-8'))

To this:

with open(path+testname, 'wb') as output:
    output.write(name.encode('utf-8'))

Also change this:

cleanedtest = open(path+"cleanToTest.txt",'wb')
cleanedtest.write(all_data.encode('utf-8'))

To this:

with open(path+"cleanToTest.txt", 'wb') as output:
    output.write(name.encode(all_data.encode('utf-8'))

Upvotes: 1

Related Questions