I'm new to python.
I have two files, one that contains symbols (words) and another that is a map file.
Both files are text files. The map file does contain form feeds.
I want to find the line in the map file that is one above the line that contains a symbol in the map file.
I have the following code.
Osymbolfile="alistofsymbols"
mapfile="amapfile"
maplines = (line.rstrip('\n\f') for line in open(mapfile))
for line in Osymbolfile:
line = (line.rstrip('\n') )
print "line= ",line
linecount = 0
for index, scanline in enumerate(maplines):
if line in scanline:
print "scanline=",scanline
print "index=",index
else:
linecount = linecount + 1
print "= ",linecount
After print "index=",index
,I've tried print maplines[index-1]
, but I get an error.
How do I obtain the line above the index
'th line in maplines
?
Your maplines
object is a generator expression ; these produce items on demand and are not indexable.
You could use a list comprehension instead:
maplines = [line.rstrip('\n\f') for line in open(mapfile)]
Now you have a indexable list object instead. Even better, you can now loop over this object multiple times; you cannot do that with a generator.
The proper way to handle your case however, is to store the previous line only:
with open(mapfile) as maplines:
prev = None
for line in maplines:
if something in line:
return prev
prev = line
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.