80 likes | 92 Views
Why use Files?. …so we can have access to ‘stored’ data even after we close our programs. Your Python Program. Write to file (Save). External File ( secondary storage ). Read from file (Load). How do we Load files?.
E N D
Why use Files? …so we can have access to ‘stored’ data even after we close our programs Your Python Program Write to file (Save) External File (secondary storage) Read from file (Load)
How do we Load files? Python requires the use of the open()function – which is a built-in function. Your Python Program Access Mode See page 84 for full list (A variable we will use to refer to the opened file) Known as the file handler. MyFile = open(‘MyToDoList.txt’, ‘r’) Filename (including path if necessary) External File (secondary storage) Read from file (Load/Open)
How do we Write to a file? Your Python Program Access Mode has changed to ‘w’ MyFile = open(‘MyToDoList.txt’, ‘w’) MyFile.write(‘This is Line 1\n’) MyFile.write(‘This is Line 2\n’) MyFile.write(‘This is Line 3\n’) MyFile.close() Write to external file 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 (secondary storage) Your Python Program Alternatively MyFile = open(‘N:\MyDocuments\Computing\MyToDoList.txt’,’r’)
Read from a file: Write to a file: MyFile = open(‘MyToDoList.txt’, ‘r’) Filename (including path if necessary)
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] MyFile = open(‘MyToDoList.txt’, ‘r’) Filename (including path if necessary)
Absolute file path Relative file path \\MyToDoList.txt MyFile = open(‘MyToDoList.txt’, ‘r’) Filename (including path if necessary)