Python file wont write blank new line

60 views Asked by At

I'm making these report files and am trying to append a blank line in between each cycle of my loop, just to help with readability.

Usually, I can just open the file and f.write('\n') to do this - for whatever reason now when I view this file it will not work. I have a few conditions so I've tried adding '\n' to the end of my output strings. Some examples below. Any ideas?? I've tried in write mode too and it doesn't work.

Fails

            #enter MSI status into output csv
            with open(f'{date}-output.csv', 'a') as f:
                #workaround f strings with \n
                newline= '\n'
                f.write(f'MSI status for {sample_id},{msi_result}{newline}')

Fails

            #enter MSI status into output csv
            with open(f'{date}-output.csv', 'a') as f:
                f.write(f'MSI status for {sample_id},{msi_result}\n')
               

Fails

            #enter MSI status into output csv
            with open(f'{date}-output.csv', 'a') as f:
                f.write(f'MSI status for {sample_id},{msi_result}')
                f.write('\n') 

I've even got one that fails on my except, where I'm just doing

            #insert new line on either success or failure
            with open(f'{date}-output.csv', 'a') as f:
                f.write('\n')
2

There are 2 answers

0
Rester On

try this:

f.write("\n\r")

it should work

0
John Gordon On

Your confusion might be because print() and write() behave differently.

print() automatically adds a newline at the end of the text, but write() does not.

If you want to write a line of text followed by a blank line, you need two newlines:

f.write('Hello I am glad to meet you.  A blank line is next.\n')
f.write('\n')

Of course you can also just put two newline characters into a single message:

f.write('Hello\n\n')