Opening and Closing Files


file = open(inPath, 'rU') file = open(outPath, 'wb') file.close()

To use most of the built-in file functions in Python, you will need to first open the file, perform whatever file operations are necessary, and then close it. Python uses the simple open(path [,mode [,buffersize]]) call to open files for both reading and writing. The path is a path string pointing to the file. The mode determines what mode the file will be opened in, as shown in Table 4.1 .

Table 4.1. File Modes for Python's Built-In File Functions

Mode

Description

r

Opens an existing file for reading.

w

Opens a file for writing. If the file already exists, the contents are deleted. If the file does not already exist, a new one is created.

a

Opens an existing file for updating, keeping the existing contents intact.

r+

Opens a file for both reading and writing. The existing contents are kept intact.

w+

Opens a file for both writing and reading. The existing contents are deleted.

a+

Opens a file for both reading and writing. The existing contents are kept intact.

b

Is applied in addition to one of the read, write, or append modes. Opens the file in binary mode.

U

Is applied in addition to one of the read, write, or append modes. Applies the "universal" newline translator to the file as it is opened.


The optional buffersize argument specifies which buffering mode should be used when accessing the file. 0 indicates that the file should be unbuffered, 1 indicates line-buffering, and any other positive number indicates a specific buffer size to be used when accessing the file. Buffering the file improves performance because part of the file is cached in computer memory. Omitting this argument or specifying a negative number results in the system default buffer size to be used.

After using the file, you should close it using the built-in close() function. This will free up the system resources and keep the file from being held open any longer than necessary.

Note

Using the universal newline mode U is extremely useful if you need to deal with files that are created by applications that are not consistent in managing newline characters. The universal newline mode converts all the different variations (\r, \n, \r\n) to the standard \n character.


inPath = "input.txt" outPath = "output.txt" #Open a file for reading file = open(inPath, 'rU') if file:     # read from file here (see Reading an Entire File     # later in this chapter for more info)     file.close() else:     print "Error Opening File." #Open a file for writing file = open(outPath, 'wb') if file:     # write to file here (see Writing a File later     # in this chapter for more info)     file.close() else:     print "Error Opening File."


open_file.py



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