How to Read and Write Files in Python

By Techwalla Contributor

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.

Open Files in Python

Step 1

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.

Step 2

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.

Step 3

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

Step 4

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

Step 1

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

Step 2

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 bytef.seek(100)# Seek to 10 bytes from the current bytef.seek(10, 1)

Step 3

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 filebuf = f.read(16)

Write to Python Files

Step 1

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")

Step 2

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 picklepickle.dump(any_object,f)

Step 3

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.f.close()