---
title: "摘自python cookbook2(文本文件)"
author: "canofy"
date: "2009-04-23T16:11:42Z"
tags: ["MySQL", "OS", "Python", "Unix", "Windows"]
slug: "python-cookbook2"
draft: false
lastmod: "2009-04-23T16:11:42Z"
id: 373413
url: "https://canofy.iteye.com/blog/373413"
---

摘自python cookbook2(文本文件) url：http://wiki.woodpecker.org.cn/moin/PyCookbook 1.从文件读取文本或数据 一次将文件内容读入一个长字符串的最简便方法 如：all\_the\_text = open('thefile.txt').read( ) # 文本文件的全部文本 all\_the\_data = open('abinfile', 'rb').read( ) # 2进制文件的全部数据 更好的方法是将文件对象和一个变量绑定，可以及时关闭文件。比如，读取文本文件内容： 如：file\_object = open('thefile.txt') # 打开文件 all\_the\_text = file\_object.read( ) # 文本文件的全部文本 file\_object.close( ) # 使用完毕，关闭文件 将文本文件的全部内容按照分行 作为一个list读出有5种方法： list\_of\_all\_the\_lines = file\_object.readlines( ) # 方法 1 list\_of\_all\_the\_lines = file\_object.read( ).splitlines(1) # 方法 2 list\_of\_all\_the\_lines = file\_object.read().splitlines( ) # 方法 3 list\_of\_all\_the\_lines = file\_object.read( ).split('\\n') # 方法 4 list\_of\_all\_the\_lines = list(file\_object) # 方法 5 2.文件中写入文本或2进制数据 将一个(大)字符串写入文件的最简单的方法如下: 如：open('thefile.txt', 'w').write(all\_the\_text) # 写入文本到文本文件 open('abinfile', 'wb').write(all\_the\_data) # 写入数据到2进制文件 更好的方法是将文件对象和一个变量绑定，可以及时关闭文件。比如，文本文件写入内容： 如：file\_object = open('thefile.txt', 'w') file\_object.write(all\_the\_text) file\_object.close( ) 写入文件的内容更多时不是一个大字符串，而是一个字符串的list(或其他序列)，这时应该使用writelines方法(此方法同样适用于2进制文件的写操作) 如：file\_object.writelines(list\_of\_text\_strings) open('abinfile', 'wb').writelines(list\_of\_data\_strings) 3.读取文件的指定一行 如：import linecache #thefiepath 文件路径 #desired\_line\_number 整数，文件的特定行 theline = linecache.getline(thefilepath, desired\_line\_number) 4.需要统计文件的行数 如：count = len(open(thefilepath).readlines( )) #方法1 count = 0 #方法2 for line in open(thefilepath).xreadlines( ): count += 1 5.读取INI配置文件 import ConfigParser import string \_ConfigDefault = { "database.dbms": "mysql", "database.name": "", "database.user": "root", "database.password": "", "database.host": "127.0.0.1" } def LoadConfig(file, config={}): """ returns a dictionary with keys of the form

. and the corresponding values """ #返回一个字典,格式如下: key:

.option&gt; # value : 对应的值 config = config.copy( ) cp = ConfigParser.ConfigParser( ) cp.read(file) for sec in cp.sections( ): name = string.lower(sec) for opt in cp.options(sec): config\[name + "." + string.lower(opt)] = string.strip( cp.get(sec, opt)) return config if _ \_name_ \_=="_ \_main_ \_": print LoadConfig("some.ini", \_ConfigDefault) 6.有ZIP压缩文件， 不需要解压，直接检查其包含的部分或全部文件信息 如：import zipfile z = zipfile.ZipFile("zipfile.zip", "r") for filename in z.namelist( ): print 'File:', filename, bytes = z.read(filename) print 'has',len(bytes),'bytes' 7.分解出文件路径所有组成部分 如： import os, sys def splitall(path): allparts = \[] while 1: parts = os.path.split(path) if parts\[0] == path: # sentinel for absolute paths #绝对路径的哨兵 allparts.insert(0, parts\[0]) break elif parts\[1] == path: # sentinel for relative paths #相对路径的哨兵 allparts.insert(0, parts\[1]) break else: #处理其余部分 path = parts\[0] allparts.insert(0, parts\[1]) return allparts 8.遍历检查目录, 或者遍历以某目录为根目录的完整的目录树,获取符合特定模式的全部文件 如： import os.path, fnmatch def listFiles(root, patterns='\*', recurse=1, return\_folders=0): # Expand patterns from semicolon-separated string to list pattern\_list = patterns.split(';') # Collect input and output arguments into one bunch class Bunch: def _ \_init_ \_(self, \*\*kwds): self._ \_dict_ \_.update(kwds) arg = Bunch(recurse=recurse, pattern\_list=pattern\_list, return\_folders=return\_folders, results=\[]) def visit(arg, dirname, files): # Append to arg.results all relevant files (and perhaps folders) for name in files: fullname = os.path.normpath(os.path.join(dirname, name)) #目录规范化 if arg.return\_folders or os.path.isfile(fullname): #判断是否返回目录。 是否是文件 for pattern in arg.pattern\_list: #模式匹配用 "or" ,符合一个就ok if fnmatch.fnmatch(name, pattern): arg.results.append(fullname) #结果中添加文件名称 break # Block recursion if recursion was disallowed if not arg.recurse: files\[:]=\[] #把list中目录包含的文件/子目录置空，子目录没了哈 os.path.walk(root, visit, arg) return arg.results 9.给定搜索路径(分隔符分开的欲搜索路径组成的字符串)，查找第一个名称符合的文件 如： import os, string def search\_file(filename, search\_path, pathsep=os.pathsep): """ Given a search path, find file with requested name """ for path in string.split(search\_path, pathsep): candidate = os.path.join(path, filename) if os.path.exists(candidate): return os.path.abspath(candidate) return None if _ \_name_ _ == '_ _ \_main_ \_': search\_path = '/bin' + os.pathsep + '/usr/bin' # ; on Windows, : on Unix find\_file = search\_file('ls',search\_path) if find\_file: print "File found at %s" % find\_file else: print "File not found" 10.在更新文件前,需要进行备份 : 按照标准协议是在原文件末尾加3位数字作为版本号来备份原文件 如： def VersionFile(file\_spec, vtype='copy'): import os, shutil if os.path.isfile(file\_spec): # or, do other error checking: if vtype not in 'copy', 'rename': vtype = 'copy' # Determine root filename so the extension doesn't get longer n, e = os.path.splitext(file\_spec) # Is e an integer? try: num = int(e) root = n except ValueError: root = file\_spec # Find next available file version for i in xrange(1000): new\_file = '%s.%03d' % (root, i) if not os.path.isfile(new\_file): if vtype == 'copy': shutil.copy(file\_spec, new\_file) else: os.rename(file\_spec, new\_file) return 1 return 0 if _ \_name_ _ == '_ \_main_ \_': # test code (you will need a file named test.txt) print VersionFile('test.txt') print VersionFile('test.txt') print VersionFile('test.txt')