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 .
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 |