user123454321
user123454321

Reputation: 152

How can I read a file in python?

Given some file that contain some text. How can I read Y bytes from this file after X bytes and print them?
I thought to use these functions: file = open("my_file", 'rb') and file.read(..) but I don't sure how to do it with these functions.

Upvotes: 0

Views: 46

Answers (1)

Amadan
Amadan

Reputation: 198566

You almost have it, you are just missing seek to select the position to read from:

file = open("my_file", 'rb')
file.seek(X)
content = file.read(Y)
file.close()
print(content)

However, if an error happened, your file would be left open for longer than necessary, so almost always you should use the with syntax instead, which will automatically dispose of file at the end of the block:

with open("my_file", 'rb') as file:
    file.seek(X)
    content = file.read(Y)
print(content)

Note that content will be bytes, not text.

Upvotes: 2

Related Questions