How to write multiple line in a .txt with Python?

I tried this:

for a in range(5):
    path_error_folder = r'C:\Users\Thomas\Desktop\test'
    if a==3:
        with open(path_error_folder +'/error_report.txt', 'w') as f:
            f.write('a\n')
    else:
        with open(path_error_folder +'/error_report.txt', 'w') as f:
            f.write('b\n')

What I expected:

enter image description here

What I get:

enter image description here

Does somebody have an idea why?


Solution 1:

Change your strategy:

path_error_folder = r'C:\Users\Thomas\Desktop\test'
with open(path_error_folder +'/error_report.txt', 'w') as f:
    for a in range(5):
        if a==3:
            f.write('a\n')
        else:
            f.write('b\n')

Solution 2:

Opening the file with 'w' flag you are writing always at the beginning of the file, so after the first write you basically overwrite it each time.

The only character you see is simply the last one you write.

In order to fix it you have two options: either open the file in append mode ('a'), if you need to preserve your original code structure

for a in range(5):
    path_error_folder = r'C:\Users\Thomas\Desktop\test'
    if a==3:
        with open(path_error_folder +'/error_report.txt', 'a') as f:
            f.write('a\n')
    else:
        with open(path_error_folder +'/error_report.txt', 'a') as f:
            f.write('b\n')

or, definitely better in order to optimize the process, open the file only once

path_error_folder = r'C:\Users\Thomas\Desktop\test'
with open(path_error_folder +'/error_report.txt', 'w') as f:
    for a in range(5):
        if a==3:
            f.write('a\n')
        else:
            f.write('b\n')