简体   繁体   English

如何使用 Python 在 a.txt 中写入多行?

[英]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:我所期望的:

在此处输入图像描述

What I get:我得到什么:

在此处输入图像描述

Does somebody have an idea why?有人知道为什么吗?

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

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.打开带有'w'标志的文件,你总是在文件的开头写入,所以在第一次写入之后,你基本上每次都会覆盖它。

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为了修复它,您有两个选择:如果您需要保留原始代码结构,请以 _ append_ 模式 ( '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, 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')

You need to append the file with open(path_error_folder +'/error_report.txt', 'a') .您需要 append 使用open(path_error_folder +'/error_report.txt', 'a')的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM