Python: Is there a better way for read()? -


in following code create temp file , save entire content of txt file in temp file. example. know makes no sense read text file , write in temp file. want demonstrate question.

well when use read() metod means entire contens of temp file saved in ram memory, right? can't control content size of temp file. thinking if there better way protect ram memory. don't want inundate ram memory.

# use temporaryfile context manager easy clean-up tempfile.temporaryfile(delete=true) tmp:     open('filename.txt', 'r') my_file:         line in my_file:             tmp.write(line)      tmp.seek(0)      exec(tmp.read()) 

the for line in my_file calls file objects .next does not buffer entire file in memory when reading:

in order make loop efficient way of looping on lines of file (a common operation), next() method uses hidden read-ahead buffer

from docs:

for reading lines file, can loop on file object. memory efficient, fast, , leads simple code

for tmp.read() function, docs:

when size omitted or negative, entire contents of file read , returned; it’s problem if file twice large machine’s memory.

so unless read line when write, or read fixed amount incrementally i.e tmp.read(100), read entire file memory.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -