Python File write() 方法

Python 教程 · 2019-02-03 16:27:58

概述

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

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

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

语法

write() 方法语法如下:

fileObject.write( [ str ])

参数

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

返回值

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

实例

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

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开文件
fo = open("test.txt", "w")
print "文件名为: ", fo.name
str = "码农教程"
fo.write( str )

# 关闭文件
fo.close()

以上实例输出结果为:

文件名为:  test.txt

查看文件内容:

$ cat test.txt 
码农教程

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

查看所有标签

Iterative Methods for Sparse Linear Systems, Second Edition

Iterative Methods for Sparse Linear Systems, Second Edition

Yousef Saad / Society for Industrial and Applied Mathematics / 2003-04-30 / USD 102.00

Tremendous progress has been made in the scientific and engineering disciplines regarding the use of iterative methods for linear systems. The size and complexity of linear and nonlinear systems arisi......一起来看看 《Iterative Methods for Sparse Linear Systems, Second Edition》 这本书的介绍吧!

html转js在线工具
html转js在线工具

html转js在线工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试