Python文件操作类操作实例详解
本文讲述了Python文件操作类的操作实例,详细代码如下:
#!/usr/bin/envpython
#!/usr/bin/envpython
#coding:utf-8
#Purpose:文件操作类
#声明一个字符串文本
poem='''
Programmingisfun测试
Whentheworkisdone
ifyouwannamakeyourworkalsofun:
usePython!
'''
#创建一个file类的实例,模式可以为:只读模式('r')、写模式('w')、追加模式('a')
f=file('poem.txt','a')#openfor'w'riting
f.write(poem)#写入文本到文件writetexttofile
f.close()#关闭文件closethefile
#默认是只读模式
f=file('poem.txt')
#ifnomodeisspecified,'r'eadmodeisassumedbydefault
whileTrue:
line=f.readline()#读取文件的每一个行
iflen(line)==0:#ZerolengthindicatesEOF
break
printline,#输出该行
#注意,因为从文件读到的内容已经以换行符结尾,所以我们在输出的语句上使用逗号来消除自动换行。
#NoticecommatoavoidautomaticnewlineaddedbyPython
f.close()#closethefile
#帮助
help(file)热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西