10.3 Files
10.3 Files
10.3 Files
Pseudocode Python
OPEN <file identifier> FOR WRITE
WRITEFILE <file identifier>, <variable>
e.g.
myFile = ‘example.txt’
lineText = ‘Hello world’
WRITEFILE myFile, lineText
Append data to file
Pseudocode Python
OPEN <file identifier> FOR WRITE
WRITEFILE <file identifier>, <variable>
e.g.
myFile = ‘example.txt’
OUTPUT “Enter your name”
INPUT lineText
WRITEFILE myFile, lineText
Read data in a file
Pseudocode Python
OPEN <file identifier> FOR READ
READFILE <file identifier>
e.g.
.read – displays all the contents
myFile = ‘example.txt’
READFILE myFile .readline – shows one line at a
time
Read data in a file
Python Python
Python Python
Python Python
• Rename the file example.txt (the
src) to question.txt (the dst)
• If the src file does not exist or
the or the dst file already exists
the os.rename() function raises a
FileNotFound error
Avoiding error when renaming a file
Python
• try...except Statement
Delete a file
Python
• If the file does not exist an
error will be generated.
• What can you do to overcome
this?
Delete a file – check if file exists
Python
• Check if the file exists
• If it does not then no error will
be generated
Delete a specific line from a file
Practice
1. Create an new text file called schools.txt.
2. Create a procedure that allows a user to add a new school name to
the text file.
3. Create a procedure that reads the file and displays all the school
names in the file.
4. Create a function that searches for a school name and returns True
if the school name exists and False if the school name does not
exist in the text file.
5. Create a function that allows a user to enter the school name they
want to delete and displays the edited text file.