详解详解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中glob模块查找文件路径的用法

glob使用UNIX shell规则查找与一个模式匹配的文件名。只要程序需要查找文件系统中名字与某个模式匹配的一组文件,就可以使用这个模块。 glob的模式规则与re模块使用的正则表达式...

浅谈python中对于json写入txt文件的编码问题

最近一直在研究python+selenium+beautifulsoup的爬虫,但是存入数据库还有写入txt文件里面的时候一直都是unicode编码的格式。 接下来就是各种翻阅文档,查找...

Flask数据库迁移简单介绍

前言 用过Django的小伙伴都知道,Django的ORM是自带的,比较特殊,而且集成了很多功能,比如数据库迁移… 何为ORM,个人之见解,简化sql语句的书写,将关系型数据库的一张张...

VSCode下配置python调试运行环境的方法

VSCode下配置python调试运行环境的方法

VSCode配置python调试环境 很久之前的一个东东,翻出来看看 VSCode配置python调试环境 * 1.下载python解释器 * 2.在V...

解决py2exe打包后,总是多显示一个DOS黑色窗口的问题

setup.py: #!/usr/bin/env python # coding=utf-8 from distutils.core import setup import py2e...