reading a line in file

Jay Loden python at jayloden.com
Mon Aug 20 15:36:56 EDT 2007


Shawn Milochik wrote:
> Hopefully this will help (using your input file)
> 
> #!/usr/bin/env python
> import re
> buildinfo = "input.txt"
> input = open(buildinfo, 'r')
> 
> 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

If the only thing needed is this specific match text, this should be more efficient (re module and regular expressions have a lot of overhead): 

#!/usr/bin/env python
buildinfo = "input.txt"
input = open(buildinfo, 'r')

token = "build.number="
BUILDNUM = ""
for line in input:
    if line.startswith(token):
        BUILDNUM = line[len(token):-1]


print "Build number: %s" % BUILDNUM



More information about the Python-list mailing list