Download presentation
Presentation is loading. Please wait.
Published byCharlotte Ford Modified over 9 years ago
1
Why use Files? Your Python Program External File (secondary storage) Write to file (Save) Read from file (Load) …so we can have access to ‘stored’ data even after we close our programs
2
How do we Load files? Your Python Program External File (secondary storage) Read from file (Load/Open) Python requires the use of the open() function – which is a built-in function. MyFile = open(‘MyToDoList.txt’, ‘r’) (A variable we will use to refer to the opened file) Known as the file handler. Filename (including path if necessary) Access Mode See page 84 for full list
3
How do we Write to a file? Your Python Program External File (secondary storage) Write to external file 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() Note that write() is a built-in function Note that \n is used to create a new line
4
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 MyFile.close() Remember to close the ‘stream’ when finished. close() is another in-built function
5
Your Python Progra m External File (secondary storage) NOTE: your python program and external file must be in the same directory or else you will need to enter the entire file path Alternatively MyFile = open(‘N:\MyDocuments\Computing\MyToDoList.txt’,’r’)
6
Write to a file: MyFile = open(‘MyToDoList.txt’, ‘r’) Filename (including path if necessary) Read from a file:
7
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]
8
MyFile = open(‘MyToDoList.txt’, ‘r’) Filename (including path if necessary) Absolute file path Relative file path \\MyToDoList.txt
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.