Transcript Files?

Why use Files?
Your
Python
Program
Write to file
(Save)
External File
Read from
file (Load)
(secondary
storage)
…so we can
have access to
‘stored’ data
even after we
close our
programs
How do we Load files?
Python requires the use of the open()
function – which is a built-in function.
Your
Python
Program
(A variable we will use to refer
to the opened file)
Known as the file handler.
Access Mode
See page 84 for full list
MyFile = open(‘MyToDoList.txt’, ‘r’)
Filename
(including path if
necessary)
Read from
file
(Load/Open)
External File
(secondary
storage)
How do we Write to a file?
Access Mode has
changed to ‘w’
MyFile = open(‘MyToDoList.txt’, ‘w’)
Your
Python
Program
MyFile.write(‘This is Line 1\n’)
MyFile.write(‘This is Line 2\n’)
MyFile.write(‘This is Line 3\n’)
Write to
external file
MyFile.close()
External File
(secondary
storage)
Note that write() is a built-in function
Note that \n is used to create a new line
MyFile = open(‘MyToDoList.txt’, ‘r’)
Now our file is open for reading. (‘r’)
Let’s output, on screen, the contents of the file.
print(MyFile.read())
read() is another in-built
function
Remember to close the ‘stream’ when finished.
MyFile.close()
close() is another in-built
function
NOTE: your python program and external file
must be in the same directory or else you will need to enter the entire file path
External File
Your
Python
Progra
m
(secondary
storage)
Alternatively
MyFile = open(‘N:\MyDocuments\Computing\MyToDoList.txt’,’r’)
Read from a file:
Write to a file:
Appending to a file:
Append means ‘to add to’, so if we want to add more data to a file which
already has some data in it, we will be appending data. In such a case, use
the access mode ‘a’ which means:
‘Open for writing, and if it exists, then append data to the end of the file’.
(There are many more built-in functions which are available to use when
reading / writing with external files. We have just briefly looked at the
fundamentals)
Task:
Relative File Paths & Absolute Paths (p88)
• What is the Relative file path of your ‘Reading a File’ program?
•What is the Absolute file path of your ‘Reading a File’ program?
Use the getcwd() function to output the [getCurrentWorkingDirectory]
Absolute file path
Relative file path
\\MyToDoList.txt