Python实例浅谈之六读写文件

一、简介

     Python提供了os、os.path等模块用于处理文件,熟练使用这些模块中的函数有助于应用。文件可以通过调用open或file来打开,open通常比file更通用,因为file几乎都是为面向对象程序设计量身打造。

二、详解

1、文件的读取(四种方式)

       使用readline()、readlines()或read()函数读取文件。
#!/usr/bin/env python
#-*- encoding:UTF-8 -*-

#文件的读取
import os, sys
filename = "file.data"

if not os.path.exists(filename):   #文件存在
    sys.exit(0)

###按行读取方式readline()
fd = open(filename, "r")
while True:
    line = fd.readline()
    if line:
        print line,          #保留换行符
    else:
        break
fd.close()
print "-"*8

###多行读取方式readlines()
fd = file(filename, "r") #等价与open
lines = fd.readlines()
for line in lines:
    print line,
fd.close()
print "-"*8

###一次性读取方式read()
fd = open(filename, "r")
content = fd.read()      #读取文件所有内容
print content,

print "length:", fd.tell()  #文件总长度
fd.seek(0)               #文件指针返回文件开头,否则再读取不到内容
content = fd.read(5)     #读取前5个字节内容
print content,
print "---", fd.tell()   #当前文件指针位置
content = fd.read()      #读取5个字节后的所有内容
print content,
print "-"*8

###简介的读取文件方法
for line in open(filename): 
    print line,


2、文件的写入(二种方式)

       write()把字符串写入文件,writelines()把列表中存储的内容写入文件。
#!/usr/bin/env python
#-*- encoding:UTF-8 -*-

#文件的读取
import os, sys
filename = "file.data"

fd = file(filename, "w+") #读取方式打开,清除文件原来内容
fd.write("goodbye\n")
fd.close()


fd = file(filename, "a+")   #追加方式打开
content = ["helloworld\n", "how are you\n"]
fd.writelines(content)      #写入列表内容
fd.close()


3、文件操作

(1)查找及解析配置文件

#!/usr/bin/env python
#-*- encoding:UTF-8 -*-

import os, sys
filename = "file.data"

fd = open(filename)
for line in fd.readlines():
    if "he" in line and "world" in line: #查找文件内容
        print "found:", line
    if line.strip().upper().endswith("BYE"): #过滤空格并统一大写,比较末尾字符串
        print "found:", line
fd.close()
     
fd = file(filename, "w+")
content = ['#configure\n', '"name"\t=', ' "taiyang"\n']
fd.writelines(content)      #写入列表内容
fd.close()

#解析常用配置文件 "name" = "taiyang"
fd = file(filename, "r")
lines=fd.readlines()
print "content:", lines
print "-"*10
infoDict={}      #解析
for i in range(0, len(lines)):
    if lines[i].strip().startswith("#"):
        continue
    strlist = lines[i].strip("\r").strip("\n").split("=")
    if len(strlist) != 2:
        continue
    key = ""
    keystr = strlist[0].strip()
    value = strlist[1].strip()
    if keystr.startswith('"') or keystr.startswith("'"):
        if keystr.endswith('"') or keystr.endswith("'"):
           key = keystr[1:len(keystr)-1]
    if value.startswith('"') or value.startswith("'"):
        if value.endswith('"') or value.endswith("'"):
            infoDict[key]=value[1:len(value)-1]

for key in infoDict:       
    print 'key=%s, value=%s' % (key, infoDict[key])  
      

 (2)列出文件列表

import os, fnmatch, glob, os.path
for fileName in os.listdir('.'): #列出当前目录内容,不包括.和..,不递归
    print fileName,

os.mkdir('pydir')   #在当前目录下创建目录,但只能创建一层
os.rmdir( 'pydir')  #在当前目录下删除目录,但只能删除一层
os.makedirs('pydir/a')     #可创建多层目录
os.removedirs('pydir/a')   #可删除多层目录

if os.path.exists('hello.txt')  #判断文件存在则删除
    os.rename('hello.txt', 'hi.txt') #文件重命名
    os.remove('hi.txt')

if os.path.exists('file.txt') 
    src = file('file.txt', 'r')  #文件的复制
    dst = file('file2.txt', 'w')
    dst.write(src.read())
    src.close()
    dst.close()

import shutil
if os.path.exists('file.txt')   #shutil模块实现文件的复制和移动
    shutil.copyfile('file.txt', 'file3.txt') #文件复制
    shutil.move('file3.txt', '../')          #文件移动
    shutil.move('file3.txt', 'file4.txt')    #文件重命名

print '\n---fnmatch module'
for fileName in os.listdir('.'):
    if fnmatch.fnmatch(fileName, '*.txt'):  #利用UNIX风格的通配,只显示后缀为txt的文件
        print fileName,

print '\n---glob module'
for fileName in glob.glob('*.txt'):  #利用UNIX风格的通配,只显示后缀为txt的文件
    print fileName,
       

 (3)获取文件状态

#!/usr/bin/env python
#-*- encoding:UTF-8 -*-

#获取文件状态
import os, time, stat
import os.path

#stat模块描述了os.stat(filename)返回的文件属性列表中各值的意义
filestats = os.stat('country.xml')                         #获取文件/目录的状态
fileInfo = {
'Size':filestats[stat.ST_SIZE],                       #获取文件大小
'LastModified':time.ctime(filestats[stat.ST_MTIME]),  #获取文件最后修改时间
'LastAccessed':time.ctime(filestats[stat.ST_ATIME]),  #获取文件最后访问时间
'CreationTime':time.ctime(filestats[stat.ST_CTIME]),  #获取文件创建时间
'Mode':filestats[stat.ST_MODE]                        #获取文件的模式
}

#print fileInfo
for field in fileInfo:                                #显示对象内容
    print '%s:%s' % (field, fileInfo[field])

#for infoField,infoValue in fileInfo:
#       print '%s:%s' % (infoField,infoValue)
if stat.S_ISDIR(filestats[stat.ST_MODE]):             #判断是否路径
    print 'Directory.'
else:
    print 'Non-directory.'

if stat.S_ISREG(filestats[stat.ST_MODE]):             #判断是否一般文件
    print 'Regular file.'
elif stat.S_ISLNK(filestats[stat.ST_MODE]):           #判断是否链接文件
    print 'Shortcut.'
elif stat.S_ISSOCK(filestats[stat.ST_MODE]):          #判断是否套接字文件     
    print 'Socket.'
elif stat.S_ISFIFO(filestats[stat.ST_MODE]):          #判断是否命名管道
    print 'Named pipe.'
elif stat.S_ISBLK(filestats[stat.ST_MODE]):           #判断是否块设备
    print 'Block special device.'
elif stat.S_ISCHR(filestats[stat.ST_MODE]):           #判断是否字符设置
    print 'Character special device.'

filename = 'country.xml'
if os.path.isdir(filename):         #判断是否路径
    print 'Directory.'
elif os.path.isfile(filename):      #判断是否一般文件
    print 'File.'
elif os.path.islink (filename):     #判断是否链接文件
    print 'Shortcut.'
elif os.path.ismount(filename):     #判断是否挂接点
    print 'Mount point.'

(4)串行化文件和内存文件

#!/usr/bin/env python
#-*- encoding:UTF-8 -*-

import pickle
#串行化文件
#cpickle是用C写的pickle模块,比标准的pickle速度快很多,使用方法同pickle

filehandlerwrite = open('pickle.txt','w')
text = ['this is a pickle demonstrate','aa','bb']
pickle.dump(text, filehandlerwrite)           #把text的内容序列化后保存到pickle.txt文件中
filehandlerwrite.close()

filehandlerread = open('pickle.txt')
textlist = pickle.load(filehandlerread)    #还原序列化字符串
print textlist
filehandlerread.close()

import StringIO
#内存文件
#cStringIO是用C写的StringIO模块,执行速度比StringIO快,使用方法同StringIO
fileHandle = StringIO.StringIO("memory content.")   #create file in memory
print fileHandle.read()    #print
fileHandle.close()

三、总结

(1)Python的标准库中提供了许多相关的模块进行文件管理,可以参考相应文档。
(2)目录的递归遍历(os.path.walk和os.walk),文件与流对象(stdin、stdout、stderror),ConfigParser模块进行配置文件解析等内容需要进一步查看其他资料。
(3)若有不足,请留言,在此先感谢!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乌托邦2号

博文不易,支持的请给予小小打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值