0

my file contains tables and other datas, after opening a file with file handle. I want to point it to specific location? example, when i find the word "Pin value" it should point there. how to point specific location in a file?

no1
  • 717
  • 2
  • 8
  • 21

3 Answers3

3

I assume you mean to get the byte index of the line in the file where that phrase is.

You can use file.seek()

with open(file) as f: # open the file
    for line in f: # iterate the lines
        if 'Pin value' in line: # find the line you want
            f.seek(-len(line), 1) # moves the pointer to the start of the line
            print f.tell() # tells you the index of the byte you are at

Here is a function:

def seek_to(file_handle, phrase):
    file_handle.seek(0) # reset to start
    for line in file_handle:
        if phrase in line:
            f.seek(-len(line)+line.find(phrase), 1)

You give the function a file_handle and a phrase, it will move the file_handles current pointer to the location right before the phrase. And do nothing else.

Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
3

Assuming that you need the file handle's pointer into the file to point right before the string 'Pin value' you could do this:

You could loop over the lines in the file and use the str.find() function:

with open('filename') as f:
    for line in f
        if 'Pin value' in line:
            my_index = line.find('Pin value')
            f.seek(-len(line) + my_index, 1)

This opens the file, reads it line by line, and scans each line for 'Pin value.' If it's found, it uses str.find() to locate the first example of it, then seeks back by the line length and forward to the start of that string, leaving the file handle pointing just before the 'P' in 'Pin value.' The second argument (1) indicates to file.seek() that the location in the file should be adjusted relative to the current location.

Handling multiple instances is a little more tricky but you can use the same basic approach.

Edit: To be more clear, at this point, if you read one more character from filehandle f you should get the character 'P' in 'Pin value'.

Mark R. Wilkins
  • 1,282
  • 7
  • 15
2

https://stackoverflow.com/a/4999741/248140 shows how you can have random (non-sequential) access to a file. Note however that you still have to work out where in the file "Pin value" is located, meaning you'd have to have some sort of index at the start of the file, and then you're getting dangerously into "I should really use a proper file format for this" territory.

If it's likely you'll want to have all the contents of the file in memory at once, consider just reading the file at the start of your program and converting it into whatever internal representation suits you best.

Community
  • 1
  • 1
frymaster
  • 220
  • 1
  • 7