Understand serial files
- Serial files store data with no order to the data maintained.
- To search data from a serial file you begin at the start of the file and read all the data until the item is found.
- Data cannot be deleted from a serial file without creating a new file and copying all the data except the item you want to delete.
- Data cannot be changed in a serial file without creating a new file, copying all the data across to a new file, inserting the change at the appropriate point.
- Data can be appended to a serial file.
- A file can be open for reading or writing, but not reading and writing at the same time.
- Serial files are quite limiting, but are useful for simple data sets and configuration files. Other types of files include: sequential files where order of the data is maintained, index sequential files for large data sets and random files which allow you to access any item without searching through the file from the start.
This content comes from our classroom resource for learning python
Challenge 1[edit]
Quote of the day challenge
Using serial files, construct a program that outputs a 'quote of the day'
- open a text editor, and save a file "quotes.txt"
- enter in 3 quotes; push enter at the end of each line:
- Every dog has its day
- Penny wise pound foolish
- Every exit is an entrance to somewhere else
- save the file. Ensure the file is in the same folder as your python program.
# we start by importing the random library so we can call random methods
import random
# the line below creates a function named random_line. The function accepts a parameter called the_quote_file
def random_line(the_quote_file):
# the line below opens the file which was passed into the function and assigns the file object to a variable named lines.
lines = open(the_quote_file).read()
# the line below calls the splitlines() method. splitlines() changes a string into a list. Each line break is a new element in the list.
lines = lines.splitlines()
# finally, we return a random element from the list named "lines".
return random.choice(lines)
# the line below we call the function "random_line" and pass that function a file named 'quotes.txt'. We then print the output.
print(random_line('quotes.txt'))