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
, 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:
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
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
, value. Another way of writing the previous example is as
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.
x = sys.argv
y = sys.argv
output = record[x] + "\n" + record[y]
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.
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