0
prevent blank lines while writing in txt-file (python & html form)
Hi, my python script receives some multiline text from a textarea-fild through the POST-method and writes it to an txt-file. With the following code a blank line is inserted after every input-line. if request.method == 'POST': new_txt = request.form['newtext'] try: file = open('files/share.txt', 'w') file.write(new_txt) finally: file.close() I guess the incoming textarea-data has linebreak-characters like \n and the write-method adds an extra \n after it. I guess I could read and write the file line by line (with readline e.g.) and remove one \n with .rsplit('\n'). But isn't there a more easy way?
4 Réponses
+ 1
Did you try file.write(new_text.strip()) (or new_txt = request.form['newtext'].strip())?
+ 1
Hm, maybe something like this?
new_txt = '''
This is a
multiline text
'''
parts = [p for p in new_txt.split('\n') if p != '']
print(' '.join(parts)) # output: This is a multiline text
This should delete all blank lines.
Or you could try something like this:
parts = [p for p in new_txt.split('\n')]
if parts[-1] == '':
parts = parts[:-1]
print(' '.join(parts))
This will only delete the last line in case it is blank.
0
@Anna Yes, but it doesn't solve the problem.
0
thanks, but that solution would not be easier than read/write the file line by line :D
I'm using this code now:
if request.method == 'POST':
new_txt = request.form['newtext']
txt2file = new_txt.split('\n')
try:
file = open('files/share.txt', 'w')
file.writelines(txt2file)
finally:
file.close()
*the new varible "txt2file" usally isn't necessary, but I need the original value from new_txt for an other reason.