详解详解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


相关文章

python中不能连接超时的问题及解决方法

python中不能连接超时的问题及解决方法

 要是我们大天朝的防火墙技术进步神速         解决方法 #只有修改pip源了。 #临时使用:...

python比较两个列表是否相等的方法

本文实例讲述了python比较两个列表是否相等的方法。分享给大家供大家参考。具体如下: 这里演示了 == 和 is两种方法的区别: L1 = [1, ('a', 3)] # same...

Python使用循环神经网络解决文本分类问题的方法详解

Python使用循环神经网络解决文本分类问题的方法详解

本文实例讲述了Python使用循环神经网络解决文本分类问题的方法。分享给大家供大家参考,具体如下: 1、概念 1.1、循环神经网络 循环神经网络(Recurrent Neural Net...

Python实现向QQ群成员自动发邮件的方法

本文实例讲述了Python实现向QQ群成员自动发邮件的方法。分享给大家供大家参考。具体实现方法如下: 原理: 我们需要先获取QQ群中的所有成员并保存到一个txt文本中去,然后再由pyth...

详解python如何在django中为用户模型添加自定义权限

django自带的认证系统能够很好的实现如登录、登出、创建用户、创建超级用户、修改密码等复杂操作,并且实现了用户组、组权限、用户权限等复杂结构,使用自带的认证系统就能帮助我们实现自定义的...