Posted By

magicrebirth on 12/22/09


Tagged

file open


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

louscomp
duke
karmacode
MartinJanda


Opening a file


 / Published in: Python
 

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

File Modes for Python's Built-In File Functions

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.

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.

  1. inPath = "input.txt"
  2. outPath = "output.txt"
  3.  
  4. #Open a file for reading
  5. file = open(inPath, 'rU')
  6. if file:
  7. # read from the file
  8. file.close()
  9. else:
  10. print "Error Opening File."
  11.  
  12. #Open a file for writing
  13. file = open(outPath, 'wb')
  14. if file:
  15. # write to the file
  16. file.close()
  17. else:
  18. print "Error Opening File."

Report this snippet  

You need to login to post a comment.