Opening and Reading Text Files by Buffer Size

 

Sometimes, we may want to read a file by buffer size so that our program does not use too much memory resources. To do that, we can use the read() function (instead of the readline() function) which allows us to specify the buffer size we want. Try the following program:

 

inputFile = open (‘myfile.txt’, 'r')

outputFile = open (‘myoutputfile.txt’, 'w')

 

msg = inputFile.read(10)

 

while len(msg):

outputFile.write(msg)

msg = inputFile.read(10)

inputFile.close()

outputFile.close()

 

First, we open two files, the inputFile.txt and outputFile.txt files for reading and writing respectively.

 

Next, we use the statement msg = inputFile.read(10) and a while loop to loop through the file 10 bytes at a time. The value 10 in the parenthesis tells the read() function to only read 10 bytes. The while condition while len(msg): checks the length of the variable msg. As long as the length is not zero, the loop will run.

 

Within the while loop, the statement outputFile.write(msg) writes the message to the output file. After writing the message, the statement msg = inputFile.read(10) reads the next 10 bytes and keeps doing it until the entire file is read. When that happens, the program closes both files.

 

When you run the program, a new file myoutputfile.txt will be created. When you open the file, you’ll notice that it has the same content as your input file myfile.txt. To prove that only 10 bytes is read at a time, you can change the line outputFile.write(msg) in the program to outputFile.write(msg + ‘\n’). Now run the program again. myoutputfile.txt now contains lines with at most 10 characters. Here’s a segment of what you’ll get.

 

Learn Pyth

on in One

Day and Le

arn It Wel