我正在尝试搜索第一个字符串实例的文本文件并返回第一行中的所有其他内容,但我当前的程序找到并返回带有字符串的最后一行。
知道我需要做什么吗?
谢谢!
这就是我的代码:
#Open search file as read only
with open(fullpath, 'r') as searchfile:
#Clear variable names
partname = partsize = None
#Search file for strings, trim lines and save as variables
for line in searchfile:
if "PART FILE NAME" in line:
x = line
partname = x[18:-1]
if "PART SIZE" in line:
y = line
partsize = y[18:-1]
#Open csv file, write variables, close csv file
storefile = open("C:/Documents and Settings/Desktop/blue pega3.csv", 'a')
storefile.write("%s,%s,%s\n" %(partname, partsize, fullpath))
storefile.close()
#Close search file
searchfile.close() `
答案 0 :(得分:5)
您的代码返回最后一个匹配项,因为您遍历整个文件,不断覆盖partname
和partsize
。如果它们尚未定义,您可能只会将它们删除:
partname = partsize = None
with open(fullpath, 'r') as searchfile:
for line in searchfile:
if partname is None and "PART FILE NAME" in line:
partname = line[18:-1]
if partsize is None and "PART SIZE" in line:
partsize = line[18:-1]
if partname is not None and partsize is not None:
break
如果已找到两行,则最后if
会停止循环播放文件 - 我们无需继续搜索。
答案 1 :(得分:3)
最简单的方法是检查partname
和partsize
是否已具有None
以外的值:
partname = partsize = None
for line in searchfile:
if partname and partsize:
break
if "PART FILE NAME" in line and partname is None:
x = line
partname = x[18:-1]
if "PART SIZE" in line and partsize is None:
y = line
partsize = y[18:-1]
答案 2 :(得分:1)
派对上晚了,抱歉,但我认为这很酷:
pattern = re.compile(r'search string')
try:
with open('search file') as inf:
# Read each line from inf, calling pattern.search(line).
# ifilter() will keep reading until it gets a match object
# instead of None. next() will either return the first
# such match object, or raise StopIteration.
match = next(itertools.ifilter(None,
(pattern.search(line)
for line in inf)))
except IOError as err:
# ...
except StopIteration:
# ...
try
/ except
稍微模糊了一点,但关键是单next()
个表达式会传递re.MatchObject
或提升StopIteration
。
当然,与任何MatchObject
一样,整个原始行可以检索为match.string
。
答案 3 :(得分:0)
试试这个:
partname = partsize = None
#Search file for strings, trim lines and save as variables
for line in searchfile:
if "PART FILE NAME" in line and partname = None:
x = line
partname = x[18:-1]
if "PART SIZE" in line and partsize = None:
y = line
partsize = y[18:-1]
答案 4 :(得分:0)
如果有一天你想支持2种以上的模式:
import csv
d = {} # name -> found part
patterns = ["PART FILE NAME", "PART SIZE", "part new"]
fieldnames = ["partname", "partsize", "partnew"]
names = dict(zip(patterns, fieldnames))
# find patterns in the file
with open(fullpath) as file:
for line in file:
if not patterns:
break # nothing left to find
for i in reversed(range(len(patterns))): # iterate in reverse
# to allow `del`
if patterns[i] in line:
d[names[patterns[i]]] = line[18:-1] # found
del patterns[i] # search for the *first* instance only
# save found values
with open(outputpath, 'wb') as storefile:
writer = csv.DictWriter(storefile, fieldnames+['fullpath'])
d['fullpath'] = fullpath
writer.writerow(d)