详解详解Python中writelines()方法的使用

yipeiwu_com6年前Python基础

 writelines()方法写入字符串序列到文件。该序列可以是任何可迭代的对象产生字符串,字符串为一般列表。没有返回值。
语法

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

fileObject.writelines( sequence )

参数

  •     sequence -- 这是字符串的序列。

返回值

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

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

#!/usr/bin/python'

# Open a file in witre 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

seq = ["This is 6th line\n", "This is 7th line"]
# Write sequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines( seq )

# Now read complete file from beginning.
fo.seek(0,0)
for index in range(7):
  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

Line No 6 - This is 7th line


相关文章

对python3 中方法各种参数和返回值详解

如下所示: # -*- coding:utf-8 -*- # Author: Evan Mi # 函数 def func1(): print('in the func...

使用python写的opencv实时监测和解析二维码和条形码

使用python写的opencv实时监测和解析二维码和条形码

今天,我实现了一个很有趣的demo,它可以在视频里找到并解析二维码,然后把解析的内容实时在屏幕上显示出来。 然后我们直入主题,首先你得确保你装了opencv,python,zbar等环境...

Python Socket传输文件示例

发送端可以不停的发送新文件,接收端可以不停的接收新文件。 例如:发送端输入:e:\visio.rar,接收端会默认保存为 e:\new_visio.rar,支持多并发,具体实现如下; 接...

python实现两张图片拼接为一张图片并保存

python实现两张图片拼接为一张图片并保存

本文实例为大家分享了python实现两张图片拼接为一张图片并保存的具体代码,供大家参考,具体内容如下 这里主要用Python扩展库pillow中Image对象的paste()方法把两张图...

django数据关系一对多、多对多模型、自关联的建立

一对多模型 一对多的关系,例如员工跟部门。一个部门有多个员工。那么在django怎么建立这种表关系呢? 其实就是利用外键,在多的一方,字段指定外键即可。例如员工和部门,员工是多,所以在...