Search code examples
pythonflaskpythonanywhere

How do I write info into a txt file or csv file using input from a flask app that is hosted on pythonanywhere


I don't understand the problem. Before when I ran this code in terminal it was working fine but when I hosted it on pythonanywhere this code does not write the input from the html form into the txt file. I'm really confused as of what is happening. My python code is this

def write_file(data):
    with open('new.txt', 'a') as f:
        f.write(data + '\n')


@app.route('/in/', methods=['GET', 'POST'])
def notin():
    if request.method == 'POST':
        notin = str(request.form['in'])
        write_file(notin)
        return render_template('in.html')
    return render_template('form.html')

My html code is(in.html):

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
 <form method="POST" action='/in/'>
      <div class="form-group">
        <input type="text" name="in">
      </div>
    </form>

  </body>
</html>

Solution

  • You're using a relative path to a file without paying attention to the working directory that your code is running with. Use the full path to new.txt so that the working directory does not affect where the file is written.