0
点赞
收藏
分享

微信扫一扫

Python:对已有内容的TXT文件追加读写

目录

 

1.问题背景      

2.解决方法

附:读写txt各参数代表的具体含义


1.问题背景      

        通常我们向txt文件写入东西时使用如下代码:

with open("test.txt", "w") as file:
    for i in range(10):
        file.write(str(i) + "\n")

        打开test.txt文件可以看到成功写入:

         上述方法可以成功向空白的txt文件写入内容,但是如果向已有内容的txt文件写入信息:

with open("test.txt", "w") as file:
    for i in range(90, 100):
        file.write(str(i) + "\n")

就会覆盖原有的内容:

而我们想要达到的是如下效果: 

2.解决方法

那怎么办呢?解决方法如下:

with open("test.txt", "a") as file:
    for i in range(90, 100):
        file.write(str(i) + "\n")

 只需要将“w”改为“a”即可,哈哈哈哈~~~

附:读写txt各参数代表的具体含义

举报

相关推荐

0 条评论