Learn > Higher Computing Science > Higher Python Course > 11. File handling – Writing

File handling - Writing

File handling lets a program write (save) and read (load) data.
Text files (.txt) store plain text, one value or line at a time.
CSV files (.csv) use commas to separate values (e.g. name,age,score).

Jane
4B2
05/06/2012
Jane,4B2,05/06/2012
John,4A1,01/01/2012

Writing data to file

When working with files, three main commands are used to handle data safely and correctly:

  • open(“filename”, “mode”) – Opens or creates a file ready for use
    • “w” writes (overwrites existing data)
    • “r” reads (opens for reading only)
      If the file doesn’t already exist, using “w” will create it automatically
  • write(“text”) – Sends text from your program into the file
    • Everything written must be a string
    • Use “\n” to move to a new line in the file
  • close() – Finishes working with the file and saves all changes
def write_data(name):
    file = open("answer.txt", "w")
    file.write("My name is ")
    file.write(name)
    file.close()
def write_data(array):
    file = open("answer.txt", "w")
    for i in range(len(array)):
        file.write(array[i])
        file.write("\n")
    file.close()