2

I need to print byte at specific position in file that i know path. So I open default file in "rb" mode and then I need to know what byte is on 15 position. It is posible ?

BengBeng
  • 127
  • 2
  • 8
  • https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects – see the end of the section, about `seek` – Ry- Feb 19 '18 at 13:03
  • Take a look at https://stackoverflow.com/questions/1035340/reading-binary-file-and-looping-over-each-byte – Walucas Feb 19 '18 at 13:04
  • seek set up pointer at specific position it's used when I need to write to file from that pointer but not exactly when i want to read. – BengBeng Feb 19 '18 at 13:04
  • no,seek sets the pointer - both for reading and writing. – jsbueno Feb 19 '18 at 13:07
  • @Walucas Let's assume that I have 20mb file and I need to know what byte is at position 16 and (size - 16) position dont think that good way is to print all 20kk bytes because it need to be fast – BengBeng Feb 19 '18 at 13:08

2 Answers2

4

Here's how you can achieve this with seek:

with open('my_file', 'rb') as f:
    f.seek(15)
    f.read(1)
Jérôme
  • 13,328
  • 7
  • 56
  • 106
1

Another way you could do this is to read the entire document and slice it:

First read the contense of the file:

file = open('test.txt', 'rb')
a = file.read()

Then take the desired value:

b = a[14]

Then don't forget to close the file afterwards:

file.close()

Or so that is closes automatically:

with open('test.txt', 'rb') as file:

    a = file.read()
    b = a[14] 
Xantium
  • 11,201
  • 10
  • 62
  • 89
  • Use a context manager so that the files is closed whatever happens. Also, I think the OP is thinking big files (see question comments) so loading the whole file might not be an option. – Jérôme Feb 19 '18 at 13:16