Once a file has been read into memory, moving from one place to
another within the file is as easy as accessing a dictionary entry.
Assuming that you are familiar with my earlier ScripTip on analyzing a
file all-at-once, this tip assumes the existence of a dictionary named
'record'. For the sake of example, 'record' contains 2500 entries,
each entry being a line from the file fed to the earlier program.
To access the last entry, simply call it by key:
More Python Quick Tips
print record['2500']This will, of course, print the value of that record. Alternatively, you can assign the key value to a variable and use that variable as the key.
x = '2500'You will recall from my earlier tip that the key value is a string. Therefore, one must access the dictionary entry with the string, not numeric, value. Another way of writing the previous example is as follows:
print record[x]
x = str(2500)While all three of these examples access a single entry, the last one, they are pretty static. If you wanted to print the first and last entries, for example, you would need to run the program once with the value of 'x' equal to '1'. Then you would need to edit the program so 'x' equals '2500' and run the program a second time. This is clumsy. A better way would be to have two separate values, 'x' and 'y', which are defined according to command-line arguments. Then, one could also format the output separately from the print command.
print record[x]
x = sys.argv[1]Naturally, more automated programs are likely to have the values of 'x' and 'y' defined from other parts of the program. It would, in fact, be very easy to have the program print all records from the outside inward, ending with the middle records, and skipping a line between pairs of records.
y = sys.argv[2]
output = record[x] + "\n" + record[y]
print output
counter1 = 1
counter2 = 2500
while counter1 < counter2:
key1 = str(counter1)
record1 = record[key1]
key2 = str(counter2)
record2 = record[key2]
output = record1 + "\n" + record2 + "\n\n"
print output
 counter1 = counter1 + 1
 counter2 = counter2 - 1
