Home > Back-end >  how to write multiple line in a .txt with Python
how to write multiple line in a .txt with Python

Time:01-21

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?

CodePudding user response:

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

CodePudding user response:

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

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

CodePudding user response:

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

  •  Tags:  
  • Related