zoukankan      html  css  js  c++  java
  • python-写入文件

    一、写入空文件(覆盖)

    # coding=UTF-8
    filename = 'test_text.txt'
    with open(filename, 'w') as file_object:
        file_object.write("Add a word")

    如果写入文件不存在,open()将自动创建它

    如果文件已存在已有内容,会清空再写入

    写入多行

    # coding=UTF-8
    filename = 'test_text.txt'
    with open(filename, 'w') as file_object:
        file_object.write("Add a word")
        file_object.write("Add two words")

    加换行符

    # coding=UTF-8
    filename = 'test_text.txt'
    with open(filename, 'w') as file_object:
        file_object.write("Add a word
    ")
        file_object.write("Add two words
    ")

    二、在原有文件上添加内容

    用‘a’

    # coding=UTF-8
    filename = 'test_text.txt'
    with open(filename, 'a') as file_object:
        file_object.write("lalala
    ")
        file_object.write("hahaha
    ")
  • 相关阅读:
    CentOS配置sshd
    求逆元 HDU 2516
    求逆元
    二分图的最大匹配
    博弈1
    几何多边形面积交模板
    LAMP服务器的搭建
    扩展欧几里得
    cf780c
    利用栈的逆波兰表达式
  • 原文地址:https://www.cnblogs.com/qianjinyan/p/13675512.html
Copyright © 2011-2022 走看看