That Blue Square Thing

AQA Computer Science GCSE

Programming projects - File Handling

Advanced File Writing

The Write files page shows you how to write data to a basic text file. This page brings in a couple of more advanced techniques.

Writing to a new text file

So, in this case the text file we want to write to doesn't exist. How can we write to that?

First we need to get the user to give us the name of the file.

# get the filename
newFileName = input("Enter the name of for the text file: ")
newFileName = newFileName + ".txt" # add .txt to it

At this point, we could just use the open method to create the new text file using the variable newFileName:

myFile = open(newFileName, "w")

Here's what the full program would look like:

# writefile program

# get the filename
newFileName = input("Enter the name of for the text file: ")
newFileName = newFileName + ".txt" # add .txt to it

dataToWrite = "Sally Shark, 120"

myNewFile = open(newFileName, "w")
myNewFile.write(dataToWrite)
myNewFile.close()

The problem is that this will not check that your filename doesn't already exist. So you could really easily overwrite a long and complex text file if you accidentally enter the wrong name (if you've read the validation page you might remember that some users are stupid...)

Checking for an existing file

It is possible to check that a file already exists using a open() with a switch of x instead of w:

myNewFile = open(newFileName, "x")

This checks if the file is already there and returns a runtime error if it does exist.

Of course, the error crashes the program. This is where a Try – Catch validation routine solves the problem...

# writefile program with try catch
checker = True # variable to control loop

dataToWrite = "Sally Shark, 120"

while checker: # while checker still True
try:
# enter the filename
newFileName = input("Enter the new file name: ")
newFileName = newFileName + ".txt" # add .txt to it

# write the data to the file
myNewFile = open(newFileName, "w")
myNewFile.write(dataToWrite)
myNewFile.close()

checker = False # no errors; change checker to end loop

except:
# if an error occurs
print("That file already exists. Enter a new name.")
print()

# confirm it worked
print("File has been written")

There are ways you can add to this - confirming if the user does actually want to overwrite the file, for example. But this is complicated enough as a starting point...

Writing a Simple List

So, you might know that arrays (lists in Python) are pretty darned useful. We already discovered that reading a list from a text file is a bit complicated because of all that \n business.

So how about, writing an array (list) to a text file?

Essentially we can just use the same technique as when we read from a list.

theNames = ["Sally", "Clive", "Farinda", "Ali"]

newNames = []

for name in theNames:
name = "\n" + name
newNames.append(name)

myFile = open("nameslist.txt", "w")
myFile.writelines(newNames)
myFile.close()

There are lots of ways this can be made more complex. Once you get into writing arrays of arrays it gets a little trickier, but provides the base to work from for now.

Writing a 2–Dimensional List

So, I showed you how to read in an array of arrays (a list of lists in Python). And it was dead easy, using a library called csv.

It's almost as easy, using the same library, to write a list of lists to a text file.

To start with, you'll need a list of lists...

import csv # import the library

countryList = [["France", "Paris"], ["Belgium", "Brussels"], ["Mali", "Bamako"], ["Morroco", "Rabat"]]

with open("countrylist.txt", "w", newline="") as outputfile:
writer = csv.writer(outputfile)
writer.writerows(countryList)

Really cleverly, the csv library takes care of the need to iterate over the countryList array (move through line by line) so you don't need to worry about any loops. Which makes life a lot easier.

Of course, you could use the skills above to check that the file name doesn't already exist and so on.