Professional Documents
Culture Documents
FILES AND IMPORT
LEARNING OUTCOMES
At the end of this session, the students should be able to:
1. Understand the use of files
2. Use files and import in creating programs.
CONTENT
I. Usage of Files
II. Writing to a File
III. Reading a file
IV. Using Import
USAGE OF FILES
We only use variables, lists, and dictionaries to store data. The values of the data are only
stored in the main memory. As we observed, once the program terminates all the data saved on
our variables are released and are no longer in the program. Thus, we use files to save the data we
obtained from our program. We can also reload the data from the files to our program.
A file is a collection of bytes stored in a secondary storage device.
WRITING TO A FILE
01 fileHandle = open(“hello.txt”,”w”)
02 fileHandle.write(“Hello World!”)
03 fileHandle.close()
The following code would not print anything on the terminal. Hello World would be printed to a file
named hello.txt.
The general format of writing files is:
<file handle variable> = open(<file name>, <mode>)
Example:
fileHandle = open(“hello.txt”,”w”)
We use the open function, we save the data to “hello.txt” and “w” is write mode. If we want to
append we use the mode “a”.
A er making a file variable, we can now use different file methods.
<file handle variable>.write()
Example:
fileHandle.write(“Hello World!”)
This is similar to print but it prints the string to the text file in the file handle variable.
A er printing all the necessary data into our text file, we should always close our file handle.
TRY THIS!
Make a program that gets the name and age of the students and saves it to a file “persons.txt”. It
must be delimited by commas. (separated by commas)
Example:
Perico, 21
Kat, 22
JM, 33
READING A FILE
01 readHandle = open(“hello.txt”,”r”)
02 for line in readHandle:
03 print(line[:-1])
04 readHandle.close()
TRY THIS!
Make a program that reads the name and age of the students and prints its contents on the
terminal.
USING IMPORT
As we see all of our programs is located at a single file. It is convenient to store different
parts of the program in different files for its readability. We can do this by using modules.
Module is a python file that contains definitions(user defined functions) and statements.
Import can be used to access functions from a separate .py(module) file. We can use functions
using this format
Contents of name.py
01 def getName():
02 name = input(“What is your name:”)
03 return name
04 def printName(name):
05 print(“Hi your name is:”,name)
Contents of main.py
01 import name
02
03 givenName = name.getName()
04 name.printName(givenName)
TRY THIS!
Transfer the read and write functions into filereader.py and import it to the main file named
main.py
REFERENCES
CMSC 11 PythonHandout 07
JMJ Bawagan Teacher’s Guide