读文件例子程序


                功能:从一格式化文本文件中读取指定的内容
input.txt
#Build Number for ANT. Do not edit!
#Mon Aug 20 04:04:51 EDT 2007
build.number=1
实现1:找到特征字符串

#read from file
buildinfo = "input.txt"
input = open(buildinfo, 'r').readlines()
token = "build.number="
BUILDNUM = ""
for line in input:
    if line.startswith(token):
        BUILDNUM = line[len(token):]
print "Build number: %s" % BUILDNUM
实现2:使用正则表达式
import re
buildinfo = "input.txt"
input = open(buildinfo, 'r').readlines()
regex = re.compile(r"^\s*build.number=(\d+)\s*$")
for line in input:
    if re.search(regex, line):
        print line
        buildNum = re.sub(r"^\s*build.number=(\d+)\s*$", "\\1", line)
        print line
        print buildNum
注意:
Regular expression parsing can have a lot of overhead, i.e. processing power/memory usage so it's recommended that they only be used when actually needed. If you only have to search for a very specific set of text or manipulate text that is very rigidly, then there's little benefit to including regular expressions. By comparison, if you have a need to match a lot of various cases or conditions, a regular expression can be by far the more efficient or logical method to use.