Thomas LESIEUR
Thomas LESIEUR

Reputation: 427

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?

Upvotes: 0

Views: 71

Answers (3)

Roberto Caboni
Roberto Caboni

Reputation: 7490

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')

Upvotes: 2

kpie
kpie

Reputation: 11120

You need to append the file with open(path_error_folder +'/error_report.txt', 'a').

Upvotes: 0

Corralien
Corralien

Reputation: 120559

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')

Upvotes: 3

Related Questions