0

I am creating a Flask website and I want to save text input from the textarea and save that text into a txt file. Everything works good but the problem is the text saved like there is an empty line after each line. I don't want this empty line. I want normal text, like no empty line after each line. Here is my code:

this is app.py

@app.route('/textCreate', methods=['GET','POST'])
@login_required
def textCreate():
  print("Inside TExt Create")
  textData = Textfile.query.all()
  with open('training_data/training.txt', 'w') as fh:
    for line in textData:
      fh.write(line.text)
  return redirect(url_for('admin'))

this is my text.html

  <tbody>
          {% for row in files %}
          <tr>
              <td>{{ row.id }}</td>
              <td>  </td>
              <td>{{ row.text }}</td>
              <td><a href="edit_script/{{row.id}}" class="btn btn-default pull-right">Edit this Question</a></td>
              <td><a href="delete_question/{{row.id}}" class="btn btn-default btn-danger pull-right"> Delete this Question</a></td>
          </tr>
          {% endfor %}
      </tbody>

and this is my text input which I input it in the text area.

What is a coronavirus? Coronaviruses are a large family of viruses that are known to cause illness ranging from the common cold to more severe diseases such as Middle East Respiratory Syndrome (MERS) and Severe Acute Respiratory Syndrome (SARS). What is a novel coronavirus? A novel coronavirus (CoV) is a new strain of coronavirus that has not been previously identified in humans. Can humans become infected with a novel coronavirus of animal source? Detailed investigations found that SARS-CoV was transmitted from civet cats to humans in China in 2002 and MERS-CoV from dromedary camels to humans in Saudi Arabia in 2012. Several known coronaviruses are circulating in animals that have not yet infected humans. As surveillance improves around the world, more coronaviruses are likely to be identified.

and this is the output with the separated lines... I mean the space/empty line which is created after every line.

What is a coronavirus?

Coronaviruses are a large family of viruses that are known to cause illness ranging from the common cold to more severe diseases such as Middle East Respiratory Syndrome (MERS) and Severe Acute Respiratory Syndrome (SARS).

What is a novel coronavirus?

A novel coronavirus (CoV) is a new strain of coronavirus that has not been previously identified in humans.

Can humans become infected with a novel coronavirus of animal source?

Detailed investigations found that SARS-CoV was transmitted from civet cats to humans in China in 2002 and MERS-CoV from dromedary camels to humans in Saudi Arabia in 2012. Several known coronaviruses are circulating in animals that have not yet infected humans. As surveillance improves around the world, more coronaviruses are likely to be identified.

I don't want these empty lines. How to remove these empty lines.

  • I'm not familiar with the `Textdata` class you're using, but could the lines you read from it include trailing newlines? You could use `i.text.rstrip()` or `i.text.rstrip('\n')`. – Michael Geary Apr 21 '21 at 08:37
  • Also I recommend not using `i` for this variable name, as `i` suggests that it is an _array index_. Instead, perhaps call it `line` or something like that? – Michael Geary Apr 21 '21 at 08:38
  • Thank you for your response Michael Geary, I tried what you said but then the whole output was only in One line....like the whole text was in one line...i.text.rstrip() it eliminates the every new line.... – Uzair Khan Apr 21 '21 at 08:52
  • and I have updated the code, line instead of i... but my problem is still there – Uzair Khan Apr 21 '21 at 08:54
  • Uzair, have you used a Python debugger before? If not, that is your next step. What editor are you using? [PyCharm](https://www.jetbrains.com/pycharm/) has an excellent debugger, and the Community edition is free. You can set a breakpoint on the line where you write the output, and look at your data in the debugger. You can also open the Python Console while stopped at the breakpoint to try out different expressions, or enter the expressions in the watch window where it displays your variables. – Michael Geary Apr 21 '21 at 10:58
  • 1
    Hi Michael Geary, Thank you so for your response. I actually wanted to tell I somehow able to solve the problem. I mentioned the solution into comments. The problem was actually of a text field which I used in the database,, I should have used the string and after doing that I changed my code slightly and then...Its working Fine as sweet.. – Uzair Khan Apr 23 '21 at 06:35

2 Answers2

0

Based on discussion in comments, what happens if you do -

fh.write(line.text.rstrip() + "\n")

Just thinking that you may have more newlines than you need. Remove them and add one back.

  • Thank you RAVI for your response but this also doing the the same thing...The whole text becomes One liner....it removes every spaces – Uzair Khan Apr 21 '21 at 09:27
  • OK. Not sure what is happening then. You will have to play around with strip methods and \n. Should have worked per others in this post -(https://stackoverflow.com/questions/2918362/writing-string-to-a-file-on-a-new-line-every-time) – RAVI KIRAN VELAMA Apr 21 '21 at 10:02
0

The problem is resolved... I want to mention the solution for people who could possibly face this type of problem...

At first I was using Flask sqlalchemy as a DATABASE.. I was storing the data into a Textfile Table. What ever user Type anything in the databse is was then stored in the Tectfile Table as a text field by importing from sqlalchemy like

from sqlalchemy import text

ans in he above code I was fetching data from the database and dstoring this text into a texfile. but with this Text field was that, they are not in the string format.. I was applying the string solution to text like format which automaticaly generate some spaces within the text...and by the way I also tried str() method to convert this text into a varchar datatypes...but nothing happend....SO I tried to change may Model from Text to String by simply importing this

import string

and then I convert my Model from text to string. Here I is my model

class Textfile(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  description = db.Column(db.String(400))
  data = db.Column(db.LargeBinary)
  text = db.Column(db.Text)
  string = db.Column(db.String(1000))
  question = db.Column(db.String(500))
  ans = db.Column(db.String(1000))

At first I was using text but then I used string to store user input from the textarea into the sql database...after doing this I change my code slightly something like this..

fh.write(line.question + "\n" + line.ans + "\n")

I just added this line into my code and then wallah....!!! The problem is solved... The saved into .txt file without any spaces... So I thought this could help for anyone who face the same kind of a problem...Cheers!