See All Titles |
![]() ![]() File HandlingPython's core language supports all the basic functions that are necessary to manipulate files. It isn't necessary to import any modules to use them. Whenever you use the open function to get access to a file, Python creates a file object that supports all the built-in methods that apply to this new object. Opening a Filebasic syntax: file = open ( filename[, mode[, buffersize]] ) The mode can be r, w, or a (read, write, and append, respectively). If none of them are mentioned, read mode is assumed. If you are working with a binary file, add the letter b to the mode indicator (for example, rb or wb). The b stands for binary mode ( text translation mode). You can also place a + sign to the mode letter to indicate a read/write open (for example, r+ or w+)—it is useful when you need to perform both operations (read and write) in the file. Remember that if you use w+, it will first truncate the file length to zero. The last argument in the open syntax is the buffersize clause, which means
Here's an example: file = open("foo.txt", "r") line = file.readline() line = line[:-1] #chop off the newline character while line: print line line = file.readline() line = line[:-1] file.close() Supported MethodsThe following methods are supported by all file objects. read()It reads up to n bytes. But, if you don't provide any argument, read() reads all available data from the file. basic syntax: file.read( [nbytes] ) >>> file = open("foo.txt").read() If you say file = open("foo.txt").read(100), Python will read the file up to its first 100 bytes. readline()It reads only one line at a time (until, and including, the newline character). >>> file=open("test.txt","r") >>> while 1: … line = file.readline() … if not line: … break … Both read() and readline() functions return an empty string for EOF. readlines()It reads the entire file into a list of strings. basic syntax: file.readlines() >>> file=open("test.txt","r") >>> for line in file.readlines(): … print line … write()It writes a string to a file. basic syntax: file.write(string) >>> file.write('Spam') writelines()It writes a list of strings to a file. basic syntax: file.writelines(list) >>> file.writelines(["We are the knights who say …","ni!"]) seek()It goes to a new file position. If how=0, it starts from the beginning of the file; if how=1, the position is relative to the current position; if how=2, the position is relative to the end of the file. The default value for how is 0. basic syntax: file.seek( position[, how] ) tell()It returns the current file pointer. Fileno()It returns an integer file descriptor. flush()It flushes the internal buffer. close()It closes the file. truncate()It truncates the file. basic syntax: file.truncate( [size] ) Now, let's mix two distinct concepts. The next line of code takes the filename and the file extension from two variables, and combines them to create the name of a file that should be opened. >>> file=open ("%s.%s" % (file_name, file_extension)).read() Remember that you need to escape your backslashes to prevent them from being interpreted as beginning a character code. See the next example. >>> file=open('C:\Autoexec.bat') # wrong way >>> file=open('C:\\Autoexec.bat') # right way The functions that you saw in this chapter are perfect for handling strings. Chapter 8, "Working with Databases," explains how to use other file handling functions to save entire objects into a file. File Object AttributesSome special attributes for files are as follows: >>> file.closed # returns 0 if the file is closed; 1 otherwise >>> file.mode # returns the I/O mode for the file >>> file.name # returns the name of the file
|
Index terms contained in this section+ (addition) sign\ (backslash) escaping a (append) mode addition (+) sign append (a) mode b (binary) mode backslash (\) escaping binary (b) mode buffersize statement clausesÓ Ò escaping backslashes (\) file handling 2nd functions handling files 2nd handling files 2nd methodsÓ Ò modes append (a) binary (b) read (r) text translationÓ Ò write (w) plus (+) sign r (read) mode read (r) mode statement buffersize syntax close() function Fileno() function flush() function opening files read() function readline() function readlines() function tell() function truncate() function write() function writelines() function text translation modeÓ Ò w (write) mode write (w) mode |
© 2002, O'Reilly & Associates, Inc. |