When you're programming in the Python language beyond the most trivial programs, you'll typically be required to read data from and write data to files that exist outside of the program itself. Python provides easy mechanisms for accessing and modifying specific files using standard functions that are part of the core language.
Video of the Day
Open Files in Python
Decide on usage policy. You need to know whether you need to read from or write to the file before you can open the file. Only open the file with the permissions you really need and don't open a file in read-write mode when you only need to read from it. This will prevent accidental writes to file you shouldn't be writing to.
Decide whether to use ASCII or binary mode. If you're reading text, you'll want to use ASCII mode. If you're reading binary data, use binary mode. This mode will translate line endings to the mode your operating system uses.
Create the mode string. The first character is read or write mode. If you want to open in binary mode, add a "b" to the end of the string. For example, to read in ASCII mode, the mode string would be "r" and to write in binary mode, the mode string would be "wb".
Open the file using the open function. Store the resulting file object in a variable. For example:
f = open("/filename/goes/here", "r")
Read From Files in Python
Iterate over all lines. A file object can be used as a collection with the "for" loop. You can iterate over all lines in a file (a common action) with the for statement.
for line in f: print line
Seek to a certain point in the file. Files are not always read sequentially so it's often necessary to seek to a certain point in the file before reading from the file. You can do this with the seek method of a file object.
Seek to the 100th byte f.seek(100)
Seek to 10 bytes from the current byte f.seek(10, 1)
Read binary data from a file. Using the read method of a file object, you can read an arbitrary number of bytes from a file.
Read 16 bytes from the file buf = f.read(16)
Write to Python Files
Write data to a file. If a file is opened in write mode, you can write ASCII or binary data to it. This is done with the write method of a file object.
f.write("This is some text")
Write objects to a file. If you need to save an object's internal state, you can "pickle" it. To pickle an object, you first have to import the pickle module. After that, you can pickle almost any object with the pickle.dump function.
import pickle pickle.dump(any_object,f)
Close the file. After writing is complete, you have to close the file. This ensures that all buffers are flushed and the file is not locked so other programs can access it. This is done with the close method of a file object.