Python文件操作类操作实例详解

yipeiwu_com5年前Python基础

本文讲述了Python文件操作类的操作实例,详细代码如下:

#!/usr/bin/env python
#!/usr/bin/env python 
#coding:utf-8 
# Purpose: 文件操作类

#声明一个字符串文本 
poem=''' 
Programming is fun测试 
When the work is done 
if you wanna make your work also fun: 
use Python! 
''' 
#创建一个file类的实例,模式可以为:只读模式('r')、写模式('w')、追加模式('a') 
f=file('poem.txt','a') #open for 'w'riting 
f.write(poem) #写入文本到文件 write text to file 
f.close() #关闭文件 close the file

#默认是只读模式 
f=file('poem.txt') 
# if no mode is specified,'r'ead mode is assumed by default 
while True: 
line=f.readline() #读取文件的每一个行 
if len(line)==0: # Zero length indicates EOF 
break 
print line, #输出该行 
#注意,因为从文件读到的内容已经以换行符结尾,所以我们在输出的语句上使用逗号来消除自动换行。 
 
#Notice comma to avoid automatic newline added by Python 
f.close() #close the file

#帮助 
help(file)

相关文章

django用户登录和注销的实现方法

django用户登录和注销的实现方法

django版本:1.4.21。 一、准备工作 1、新建项目和app [root@yl-web-test srv]# django-admin.py startproject lxy...

Python实现遍历目录的方法【测试可用】

Python实现遍历目录的方法【测试可用】

本文实例讲述了Python实现遍历目录的方法。分享给大家供大家参考,具体如下: # *-* coding=gb2312 *-* import os.path import shuti...

python中时间转换datetime和pd.to_datetime详析

python中时间转换datetime和pd.to_datetime详析

前言 我们在python对数据进行操作时,经常会选取某一时间段的数据进行分析。这里为大家介绍两个我经常用到的用来选取某一时间段数据的函数:datetime( )和pd.to_dateti...

Python入门篇之对象类型

Python入门篇之对象类型

Python使用对象模型来存储数据。构造任何类型的值都是一个对象 所有的Python对象都拥有三个特性:身份、类型、值 身份: 每一个对象都有一个唯一的身份来标志自己,任何对象的身份可以...

使用celery执行Django串行异步任务的方法步骤

前言 Django项目有一个耗时较长的update过程,希望在接到请求运行update过程的时候,Django应用仍能正常处理其他的请求,并且update过程要求不能并行,也不能漏掉任何...