Python3 File write() 方法

Python 3 教程 · 2019-02-07 06:41:56

概述

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

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

如果文件打开模式带 b,那写入文件内容时,str (参数)要用 encode 方法转为 bytes 形式,否则报错:TypeError: a bytes-like object is required, not 'str'。

语法

write() 方法语法如下:

fileObject.write( [ str ])

参数

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

返回值

返回的是写入的字符长度。

实例

文件 codercto.txt 的内容如下:

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

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

#!/usr/bin/python3

# 打开文件
fo = open("codercto.txt", "r+")
print ("文件名: ", fo.name)

str = "6:www.codercto.com"
# 在文件末尾写入一行
fo.seek(0, 2)
line = fo.write( str )

# 读取文件所有内容
fo.seek(0,0)
for index in range(6):
    line = next(fo)
    print ("文件行号 %d - %s" % (index, line))

# 关闭文件
fo.close()

以上实例输出结果为:

文件行号 0 - 1:www.codercto.com

文件行号 1 - 2:www.codercto.com

文件行号 2 - 3:www.codercto.com

文件行号 3 - 4:www.codercto.com

文件行号 4 - 5:www.codercto.com

文件行号 5 - 6:www.codercto.com

查看文件内容:

$ cat codercto.txt 
1:www.codercto.com
2:www.codercto.com
3:www.codercto.com
4:www.codercto.com
5:www.codercto.com
6:www.codercto.com

点击查看所有 Python 3 教程 文章: https://www.codercto.com/courses/l/10.html

查看所有标签

Realm of Racket

Realm of Racket

Matthias Felleisen、Conrad Barski M.D.、David Van Horn、Eight Students Northeastern University of / No Starch Press / 2013-6-25 / USD 39.95

Racket is the noble descendant of Lisp, a programming language renowned for its elegance and power. But while Racket retains the functional goodness of Lisp that makes programming purists drool, it wa......一起来看看 《Realm of Racket》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具