加载中...

Python

  1. Home
  2. Computing & Technology
  3. Python

Moving Around in a File

From Al Lukaszewski, for About.com

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:
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'
print record[x]
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:
x = str(2500)
print record[x]
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[1]
y = sys.argv[2]
output = record[x] + "\n" + record[y]
print output
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
   &#160counter1 = counter1 + 1
   &#160counter2 = counter2 - 1
More Python Quick Tips

Explore Python

More from About.com

Python

  1. Home
  2. Computing & Technology
  3. Python
  4. ScripTips
  5. Moving Around in a File

©2009 About.com, a part of The New York Times Company.

All rights reserved.