python - How does readline() work behind the scenes when reading a text file? -


i understand how readline() takes in single line text file. specific details know about, respect how compiler interprets python language , how handled cpu, are:

  1. how readline() know line of text read, given successive calls readline() read text line line?
  2. is there way start reading line of text middle of text? how work respect cpu?

i "beginner" (i have 4 years of "simpler" programming experience), wouldn't able understand technical details, feel free expand if others understand!

example using file file.txt:

fake file text in few lines 

question 1: how readline() know line of text read, given successive calls readline() read text line line?

when open file in python, creates file object. file objects act file descriptors, means @ 1 point in time, point specific place in file. when first open file, pointer @ beginning of file. when call readline(), moves pointer forward character after next newline reads.

calling tell() function of file object returns location file descriptor pointing to.

with open('file.txt', 'r') fd:     print fd.tell()     fd.readline()     print fd.tell()  # output: 0 10 


question 2: there way start reading line of text middle of text? how work respect cpu?

first off, reading file doesn't have cpu. has operating system , file system. both of determine how files can read , written to. barebones explanation of files

for random access in files, can use mmap module of python. python module of week site has great tutorial.

example, jumping 2nd line in example file , reading until end:

import mmap import contextlib  open('file.txt', 'r') fd:     contextlib.closing(mmap.mmap(fd.fileno(), 0, access=mmap.access_read)) mm:         print mm[10:]  # output: text in few lines 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

http - Safari render HTML as received -