40. Reading and writing files

  • Reading and writing files is fairly simple if you know what you want to load and save
  • There are simple techniques for reading and writing individual items of data to and from a text file, a line at a time or all at once
  • Reading multiple lines is usually done with a for loop and the contents are loaded into a list within the program. Using a list means your program can handle files containing different amounts of data.
  • Depending on what you are using files for, it pays to have planned exactly what you are loading and saving from your file. Questions to ask yourself:
    • What am I actually storing on each line of the file?
    • Is it an unorganised list or are the items in a particular order?
    • Are there a set number of lines that will be used?
    • Do you need to read/write each line individually?
    • Do you need to add or delete individual items in the file?
    • Do you need to store multiple items of information on each line? If so, how will they be separated?
#Open a file (r = read, w = write, a = append)
file = open("users.txt","r")

#Do stuff here

#Close the file
file.close()