4.4. Files

During a program execution data are stored in memory. But if the program ends the data are cleared from memory. In this chapter we will explain how programs can communicate data permanently.

In the above sections we have seen how we can communicate interactively with programs during their execution. However, if we need to store data permanently, we have to store them in files.

Files

Files are entities containing character data which are stored on external devices, such as disks or CD-ROMs.

Files are like books. You open them to start working, then read or write in them and you close them when you have finished your work. However, you have always to know where you are in the book. As children use their fingers when they start to learn reading, you manipulate a file pointer which indicates your current position in the file.

4.4.1. Reading from a file

The following statements are typical statements used to read the content of a file.

f = open("myfile")
for l in f:
    # do something with the line stored in variable l
f.close()
	
f is a variable associated with the file pointer.

4.4.2. Writing into a file

In order to write into a file, you must open it in 'w' (write) mode.

f = open("myfile", 'w')
f.write("hello, this is my new line of data")
f.close()
	
You might be surprised by the syntax shown above, where functions such as write and close are called with a dot ('.') put after the file pointer. This syntax and the related concept will be developed in Section 6.1.

Exercise 4.1. Copying a file

How would you copy a file?

4.4.3. Errors with files

Chapter 12 presents how errors are managed in Python. Let us just look for now at how to deal with file errors, mainly errors with file names. What will happen if your program attempts to open a file that does not exist?

f = open("myfileee")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'myfileee'
	
A common way to let your program handle this type of error properly is to specify what to do in case of errors:
try:
    f = open("myfileee")
except IOError:
    print "the file  myfileee does not exist!!"
	
Handling this type of IO (input/output) error makes your program more robust.