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?

3
  • 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' Commented Jan 20, 2022 at 18:44
  • 1
    Does this answer your question? Difference between modes a, a+, w, w+, and r+ in built-in open function? Commented Jan 20, 2022 at 18:51
  • Thanks ! It's exactly what I was looking for ! Commented Jan 20, 2022 at 19:40

3 Answers 3

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')
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

2 Comments

Appending is bad because is it will not empty the file when the program is ran again. This answer is better.
@BCT Who's to say that's wrong? It might actually be required sometimes...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.