zoukankan      html  css  js  c++  java
  • Python 文件 write() 方法

    概述

    Python 文件 write() 方法用于向文件中写入指定字符串。

    在文件关闭前或缓冲区刷新前,字符串内容存储在缓冲区中,这时你在文件中是看不到写入的内容的。

    语法

    write() 方法语法如下:

    fileObject.write(str)

    参数

    • str -- 要写入文件的字符串。

    返回值

    该方法没有返回值。

    实例

    文件 runoob.txt 的内容如下:

    1:www.runoob.com
    2:www.runoob.com
    3:www.runoob.com
    4:www.runoob.com
    5:www.runoob.com

    以下实例演示了 write() 方法的使用:

    #!/usr/bin/python3
    
    # 打开文件
    fo = open("runoob.txt", "r+",encoding="utf-8")
    print ("文件名: ", fo.name)
    # 在文件末尾写入一行
    fo.seek(0,2)
    fo.write("
    6:www.runoob.com")
    
    # 读取文件所有内容
    fo.seek(0,0)
    for index in range(6):
        line = next(fo)
        print ("文件行号 %d - %s" % (index, line))
    
    # 关闭文件
    fo.close()

    以上实例输出结果为:

    文件行号 0 - 1:www.runoob.com
    
    文件行号 1 - 2:www.runoob.com
    
    文件行号 2 - 3:www.runoob.com
    
    文件行号 3 - 4:www.runoob.com
    
    文件行号 4 - 5:www.runoob.com
    
    文件行号 5 - 6:www.runoob.com

    查看文件内容:

    $ cat runoob.txt 
    1:www.runoob.com
    2:www.runoob.com
    3:www.runoob.com
    4:www.runoob.com
    5:www.runoob.com
    6:www.runoob.com
  • 相关阅读:
    Leetcode 349. Intersection of Two Arrays
    hdu 1016 Prime Ring Problem
    map 树木品种
    油田合并
    函数学习
    Leetcode 103. Binary Tree Zigzag Level Order Traversal
    Leetcode 102. Binary Tree Level Order Traversal
    Leetcode 101. Symmetric Tree
    poj 2524 Ubiquitous Religions(宗教信仰)
    pat 1009. 说反话 (20)
  • 原文地址:https://www.cnblogs.com/wushuaishuai/p/8511765.html
Copyright © 2011-2022 走看看