Python File Handling
Python File Handling
slide 1
What You Need In Order To Read
Information From A File
1. Open the file and associate the file with a file variable.
2. A command to read the information.
3. A command to close the file.
slide 2
1. Opening Files
Example:
(Constant file name)
inputFile = open("data.txt", "r")
OR
(Variable file name: entered by user at runtime)
filename = input("Enter name of input file: ")
inputFile = open(filename, "r")
slide 3
1 Examples assume that the file is in the same directory/folder as the Python program.
B. Positioning The File Pointer
letters.txt
B
:
slide 4
2. Reading Information From Files
Format:
for <variable to store a string> in <name of file variable>:
<Do something with the string read from file>
Example:
for line in inputFile:
print(line) # Echo file contents back onscreen
slide 5
Closing The File
• Example:
inputFile.close()
slide 6
Reading From Files: Putting It All Together
inputFile.close()
print("Completed reading of file", inputFileName)
slide 7
What You Need To Write Information To A File
1. Open the file and associate the file with a file variable (file is
“locked” for writing).
2. A command to write the information.
3. A command to close the file.
slide 8
1. Opening The File
Format1:
<name of file variable> = open(<file name>, "w")
Example:
(Constant file name)
outputFile = open("gpa.txt", "w")
slide 9
1 Typically the file is created in the same directory/folder as the Python program.
3. Writing To A File
Format:
outputFile.write(temp)
Example:
# Assume that temp contains a string of characters.
outputFile.write (temp)
slide 10
Writing To A File: Putting It All Together
slide 11
slide 12
James Tam
Writing To A File: Putting It All Together (2)
inputFile.close ()
outputFile.close ()
print ("Completed reading of file", inputFileName)
print ("Completed writing to file", outputFileName)
slide 14
Reading From Files: Commonly Used Algorithm
• Pseudo-code:
Read a line from a file as a string
While (string is not empty)
process the line
Read another line from the file
slide 15
James Tam
File Input: Alternate Implementation
• Name of the online example: grades3.py
inputFileName = input ("Enter name of input file: ")
inputFile = open(inputFileName, "r")
print("Opening file", inputFileName, " for reading.")
line = inputFile.readline()
inputFile.close()
print("Completed reading of file", inputFileName)
slide 16
James Tam
Data Processing: Files
• Files can be used to store complex data given that there exists
a predefined format.
• Format of the example input file: ‘employees.txt’
<Last name><SP><First Name>,<Occupation>,<Income>
slide 17
James Tam
Example Program: data_processing.py
# EMPLOYEES.TXT
inputFile = open ("employees.txt", "r")
Adama Lee,CAG,30000
Morris Heather,Heroine,0
print ("Reading from file input.txt") Lee Bruce,JKD master,100000
for line in inputFile:
name,job,income = line.split(',')
last,first = name.split()
income = int(income)
income = income + (income * BONUS)
print("Name: %s, %s\t\t\tJob: %s\t\tIncome $%.2f"
%(first,last,job,income))
slide 18
James Tam
Error Handling With Exceptions
slide 21
Exception Handling: Keyboard Input
inputOK = False
while (inputOK == False):
try:
num = input("Enter a number: ")
num = float(num)
except ValueError: # Can’t convert to a number
print("Non-numeric type entered '%s'" %num)
else: # All characters are part of a number
inputOK = True
num = num * 2
print(num)
slide 22
slide 23
James Tam
You Should Now Know
slide 24