Table of Contents
|
What is a file in Python?
Since files are central to so many computing operations, all programming languages have methods for dealing with them. Python has a native file type (also called a file handle) that has various capabilities associated with files.
How do I open a file?
Before a file can be used it must be opened. This tells Python to make sure the file is present and with the proper permissions before establishing a variable representing that file.
When a file is opened, you must say whether you intend to read or write to that file, or both. For simplicity, we'll start with looking at reading and writing separately
Opening a file to read
fh = open("filename.txt", "r")
In this code the string "r", passed as the second parameter, tells Python to open the file to be read.
Opening a file to write
fh = open("filename.txt", "w")
Conversely, the second parameter here is the string "w", telling Python to open the file to write to it.
Error messages
As with any programming construct, it's good to know what kind of error messages you can expect so that you know how to fix them. Here are a few.
Opening a file to read which doesn't exist:
>>> fh = open("nothing.txt", "r")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'nothing.txt'
Opening a file to read without the proper permissions:
>>> fh = open("tester.py", "r")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 13] Permission denied: 'tester.py'
Opening a file to write when it exists already:
In fact, this does not generate an error. It will, however, allow you to overwrite what is in the file with no other warnings. Beware!
How do I read from a file?
Here is a simple code fragment to read a file and print it to the screen:
fh = open("tester.txt", "r")
for line in fh:
print line
# including a "close" line is not essential, but good practice
fh.close()
Given a "tester.txt" that looks like this:
This is a test file
It has some lines of text
in it
and some spaces
and things
Here is the output from the code fragment:
This is a test file
It has some lines of text
in it
and some spaces
and things
Note that the output has extra line spaces in it. This is because when the for loop reads each line, it reads the whole line including the line break. The print command also inserts its own line break, so we get two. One way to avoid this is to chop the line break off the end using a string slice.
fh = open("tester.txt", "r")
for line in fh:
# only print the line up to the penultimate character
# this removes the line break
print line[:-1]
fh.close()
Other ways of reading from a file
You can also read from a file by using methods on the file, such as read() and readline(). See here for more details.