Python中操作文件之write()方法的使用教程

yipeiwu_com5年前Python基础

 write()方法把字符串str写入文件。没有返回值。由于缓冲,字符串可能不实际显示文件,直到flush()或close()方法被调用。
语法

以下是write()方法的语法:

fileObject.write( str )

参数

  •     str -- 这是要被写入的文件中的字符串。

返回值

此方法不返回任何值。
例子

下面的例子显示write()方法的使用。

#!/usr/bin/python

# Open a file in write mode
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

str = "This is 6th line"
# Write a line at the end of the file.
fo.seek(0, 2)
line = fo.write( str )

# Now read complete file from beginning.
fo.seek(0,0)
for index in range(6):
  line = fo.next()
  print "Line No %d - %s" % (index, line)

# Close opend file
fo.close()

当我们运行上面的程序,它会产生以下结果:

Name of the file: foo.txt
Line No 0 - This is 1st line

Line No 1 - This is 2nd line

Line No 2 - This is 3rd line

Line No 3 - This is 4th line

Line No 4 - This is 5th line

Line No 5 - This is 6th line


相关文章

Python中实例化class的执行顺序示例详解

前言 本文主要介绍了关于Python实例化class的执行顺序的相关内容,下面话不多说了,来一起看看详细的介绍吧 Python里对类的实例化时有怎样的顺序 一般来说一个类里面有类变量和...

python提取log文件内容并画出图表

python提取log文件内容并画出图表

之前在excel里面分析log数据,简直日了*了。 现在用python在处理日志数据. 主要涉及 matplotlib,open和循环的使用。 日志内容大致如下 2016-10-2...

videocapture库制作python视频高速传输程序

videocapture库制作python视频高速传输程序

1,首先是视频数据[摄像头图像]的采集,通常可以使用vfw在vc或者vb下实现,这个库我用的不好,所以一直不怎么会用.现在我们用到的是python的videocapture库,这个库用起...

Python基于pillow判断图片完整性的方法

本文实例讲述了Python基于pillow判断图片完整性的方法。分享给大家供大家参考,具体如下: 1、安装第三方库。 pip install pillow 2、函数示例。...

详解基于python的多张不同宽高图片拼接成大图

详解基于python的多张不同宽高图片拼接成大图

半年前写过一篇将多张图片拼接成大图的博客,是讲的把所有图片先转换为256×256的图片后再进行拼接,今天看到一个朋友的评论说如何拼接非正方形图片,如47×57,之前有个朋友也问过这个,我...