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

yipeiwu_com5年前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编程中对super函数的正确理解和用法解析

当在子类需要调用父类的方法时,在python2.2之前,直接用类名调用类的方法,即非绑定的类方法,并把自身对象self作参数传进去。 class A(object): def...

将Django使用的数据库从MySQL迁移到PostgreSQL的教程

我们已对 Django1.6 app完成了数据库从mysql到PostgreSQL的迁移,如果你的环境很干净,这个过程就会很简单,只要允许syncdb 或者 migrate创建表,tru...

python实现二分查找算法

二分查找算法:简单的说,就是将一个数组先排序好,比如按照从小到大的顺序排列好,当给定一个数据,比如target,查找target在数组中的位置时,可以先找到数组中间的数array[mid...

python自定义函数实现一个数的三次方计算方法

python自定义函数实现一个数的三次方计算方法

python自定义函数在运行时,最初只是存在内存中,只有调用时才会触发运行。 def cube_count(a): if is_number(a): return a**...

Python处理文本换行符实例代码

Python处理文本换行符实例代码

本文研究的主要是Python处理文本换行符的相关内容,具体如下。 源文件每行后面都有回车,所以用下面输出时,中间会多了一行 try: with open("F:\\hjt.txt...