Files in Python

Being able to read, create, delete or modify files from within a program is terribly useful. It can be used to store state, configuration, data, logs and man more things. Certainly, third-party datastores can be both easier and more powerful to use for complex problems, but sometimes a simple file is all you need.

Python using Laptop

Checking if a file exists

Sometimes that fact a file does not exist, may indicate that this is the first time a program has been executed and additional setup is required, or it could mean that something has gone wrong, and we need to recover from an error. For these reasons, it may be helpful to explicitly check if a file exists.

For this, we shall use the isFile function from the os package

import os

filename="myFile"
filename2="fileThatDoesNotExist"
fileList = [filename, filename2]

for file in fileList:
  if os.path.isfile(file):
    print(file, "found")
  else:
    print(file, "not found")

When we run it, first with no files existing, and then again with one of them existing.

> python filefun.py
myFile not found
fileThatDoesNotExist not found
> touch myFile
> python3 filefun.py
myFile found
fileThatDoesNotExist not found

Reading A file

For this next example of reading a file, we shall put some content in our file

> cat myFile  
5 sheep
4 hats

We can read in the entire file at once using the read() function

filename="myFile"
f = open(filename, "r")
print(f.read())
f.close()

And when we run it, we get the entire file

python3 filefun.py
5 sheep
4 hats

We may instead want to read the file line by line using readline(). Note it can take an argument that indicates how may bytes you want to read, but we will keep it simple and read the entire line. Note it is good practice to explicitly close a file when you are done with it.

filename="myFile"

f = open(filename, "r")

line = f.readline()
while line:
  print("Line:", line)
  line = f.readline() 

f.close()

Which yields us the following when we run it.

>python filefun.py
Line: 5 sheep

Line: 4 hats

If instead I have a file with an integer I am interested in treating like an integer, the following example shows a simple conversion

def getIndexFromFile():
  f = open(indexFile, "r")
  indexFromFile = int(f.read())
  f.close()
  return indexFromFile

Writing A File

To write to a file, we use the open() method again, but this time with a “w” or “a” attribute. In fact, here at all the possible values

'r'open for reading (default)
'w'open for writing, truncating the file first
'x'open for exclusive creation, failing if the file already exists
'a'open for writing, appending to the end of file if it exists
'b'binary mode
't'text mode (default)
'+'open for updating (reading and writing)

In our example, we shall use the append to add a line to the file

filename="myFile"

f = open(filename, "a")
f.write("12 llamas")
f.close()
> python filefun.py
> more myFile
5 sheep
4 hats
12 llamas

And to match our final example in the read section, we shall read the integer value, increment it and write it again. Note we are converting it back to string before writing it.

def getNextIndex():
  indexFromFile = getIndexFromFile()
  newIndex = indexFromFile + 1
  f = open(indexFile, "w")
  f.write(str(newIndex))  
  return newIndex

Deleting Files

To delete files, we again use the os module

import os

filename = "deleteMePlease.txt"

os.remove(filename)

When we start to run, our file deleteMePlease.txt exists, but after we run our program, it is gone.

> ls deleteMePlease.txt
deleteMePlease.txt
> python deleteFile.py 
> ls deleteMePlease.txt 
ls: deleteMePlease.txt: No such file or directory