详解详解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安装PIL模块时Unable to find vcvarsall.bat错误的解决方法

可能很多人遇到过这个错误,当使用setup.py安装python2.7图像处理模块PIL时,python默认会寻找电脑上以安装的vs2008.如果你没有安装vs2008,会出现Unabl...

使用Python 统计高频字数的方法

问题 (来自Udacity机器学习工程师纳米学位预览课程) 用 Python 实现函数 count_words(),该函数输入字符串 s 和数字 n,返回 s 中 n 个出现频率最高的单...

python利用openpyxl拆分多个工作表的工作簿的方法

python利用openpyxl拆分多个工作表的工作簿的方法

实现按目录拆分工作簿,源数据如下图 按目录拆分成N个文件。 上代码,没有找是否有整个sheet 复制的,先逐个cell复制解决问题。: # encoding: utf-8 """...

pyqt5 使用label控件实时显示时间的实例

pyqt5 使用label控件实时显示时间的实例

如下所示: import sys from PyQt5 import QtGui, QtCore, QtWidgets from PyQt5.QtWidgets import * f...

RC4文件加密的python实现方法

本文实例讲述了RC4文件加密的python实现方法。分享给大家供大家参考。具体分析如下: 基于RC4流加密算法,使用扩展的16*16的S盒,32字节密钥。 目前应该是比较安全的。 &nb...