0

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?

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
Thomas LESIEUR
  • 408
  • 4
  • 14
  • 4
    I think what you are looking for; is using `"a"` (append flag) instead of `"w"`, using the write flag just overwrites the file every time you write something to it' – BoredRyuzaki Jan 20 '22 at 18:44
  • 1
    Does this answer your question? [Difference between modes a, a+, w, w+, and r+ in built-in open function?](https://stackoverflow.com/questions/1466000/difference-between-modes-a-a-w-w-and-r-in-built-in-open-function) – Tomerikoo Jan 20 '22 at 18:51
  • Thanks ! It's exactly what I was looking for ! – Thomas LESIEUR Jan 20 '22 at 19:40

3 Answers3

3

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')
Corralien
  • 109,409
  • 8
  • 28
  • 52
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')
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
0

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

kpie
  • 9,588
  • 5
  • 28
  • 50
  • Appending is bad because is it will not empty the file when the program is ran again. [This answer](https://stackoverflow.com/a/70791797/16001580) is better. – BCT Jan 20 '22 at 18:48
  • @BCT Who's to say that's wrong? It might actually be required sometimes... – Tomerikoo Jan 20 '22 at 18:58