python 取文本文件的某段字符串

例如:
a.txt中有一行是
SETNAME = /usr/bin/temp/test.ini_MYNAME
请问,如何取得MYNAME这几个字???
其中,SETNAME后面可能有多个空格或Tab
后面的路径可能会变的,但是test.ini_永远是固定的。

第1个回答  2013-06-28
def zhidao_562938748(filename):
    result = ''
    reader = open(filename, 'r')
    while True:
        line = reader.readline()
        if len(line) == 0:
            break
        if not line.startswith('SETNAME'):
            continue
        pos = line.rfind('/')
        if pos < 0:
            continue
        if not line.startswith('/test.ini_', pos):
            continue
        result = line[pos + len('/test.ini_'):]
    reader.close()
    return result

本回答被提问者采纳
第2个回答  2013-06-28
import re

path = r'C:\a.txt'
f = open(path)
content = f.readlines()
f.close()
content = ''.join(content)

reg = r'SETNAME[\s]*= (/[\w]*)*test.ini_[\w]*'
re = re.compile(reg)
m = re.search(content)
if m.group:
index = m.group().index("_")
print m.group()[index+1:]

这个正则表达可能不是很严谨,不过是可以工作的,正则表达式可以再改进一下。
第3个回答  2013-06-28
import re

SETNAME    = '/usr/bin/temp/test.ini_MYNAME'

match = re.compile(r'(.*)test.ini_(.*)',re.M|re.S)

rs = match.search(SETNAME)

if rs:
    print rs.group(2).strip()

第4个回答  2013-06-28
# -*- coding: gbk -*-
#python a.py

ifilepath=("a.txt")
#print ifilepath
ifile = file(ifilepath,"r")
str1 = ifile.read()
#print str1
place1 = str1.find("\nSETNAME")
print place1
place2 = str1.find("\n",place1+1)
print place2
place3 = str1.find("/test.ini_",place1)
print place3
str2= str1[place1+1:place2]
print str2
str3= str1[place3+10:place2]
print str3

 

相似回答