Reading an Entire File


buffer += open(filePath, 'rU').read() inList = open(filePath, 'rU').readlines() while(1):     bytes = file.read(5)     if bytes:         buffer += bytes

Python provides several methods to read the entire contents of a file. The first is to open the file and call the read() function. This will read the entire contents of the file until an EOF marker is encountered and returns the contents of the file as a string.

Another method to read an entire file is to use the readlines() function. This reads the entire contents of the file, separating each line into individual strings, until an EOF marker is encountered. Once the end of the file is found, a list of strings representing each line is returned.

In case of very large files, you might want to read only a specific number of bytes at a time. Use the read(bytes) function to read a specific number of bytes at a time, which can then be processed more easily. This will read a specific number of bytes from the file if possible and return them as a string. If the first character read is an EOF marker, null is returned.

The code in read_file.py demonstrates how to read the entire contents at once, one line at a time, as well as a specific number of bytes from a file.

filePath = "input.txt" #Read entire file into a buffer buffer = "Read buffer:\n" buffer += open(filePath, 'rU').read() print buffer #Read lines into a buffer buffer = "Readline buffer:\n" inList = open(filePath, 'rU').readlines() print inList for line in inList:     buffer += line print buffer #Read bytes into a buffer buffer = "Read buffer:\n" file = open(filePath, 'rU') while(1):     bytes = file.read(5)     if bytes:         buffer += bytes     else:         break print buffer


read_file.py

Read buffer: Line 1 Line 2 Line 3 Line 4 ['Line 1\n', 'Line 2\n', 'Line 3\n', 'Line 4\n'] Readline buffer: Line 1 Line 2 Line 3 Line 4 Read buffer: Line 1 Line 2 Line 3 Line 4


Output from read_file py code




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net