Lesson 6: File Processing
Lesson 6: File Processing
File processing
Prepared by: Maria Kristela V. Fajardo, DIT
Reading Files
name = open("filename")
– opens the given file for reading, and returns a file object
>>> f = open("hours.txt")
>>> f.read()
'123 Susan 12.5 8.1 7.6 3.2\n
456 Brad 4.0 11.6 6.5 2.7 12\n
789 Jenn 8.0 8.0 8.0 8.0 7.5\n'
2
File Input Template
• A template for reading files in Python:
name = open("filename")
for line in name:
statements
3
Exercise
• Write a function input_stats that accepts a file name as
a parameter and that reports the longest line in the file.
– example input file, carroll.txt:
Beware the Jabberwock, my son,
the jaws that bite, the claws that catch,
Beware the JubJub bird and shun
the frumious bandersnatch.
– expected output:
>>> input_stats("carroll.txt")
longest line = 42 characters
the jaws that bite, the claws that catch,
4
Exercise Solution
def input_stats(filename):
input = open(filename)
longest = ""
for line in input:
if len(line) > len(longest):
longest = line
5
Recall: String Methods
Java Python
length len(str)
startsWith, endsWith startswith, endswith
toLowerCase, toUpperCase upper, lower,
isupper, islower,
capitalize, swapcase
indexOf find
trim strip
ord, chr
7
Splitting into Variables
• If you know the number of tokens, you can split them
directly into a sequence of variables.
var1, var2, ..., varN = string.split()
8
Exercise
• Suppose we have this hours.txt data:
123 Suzy 9.5 8.1 7.6 3.1 3.2
456 Brad 7.0 9.6 6.5 4.9 8.8
789 Jenn 8.0 8.0 8.0 8.0 7.5
9
Exercise Answer
hours.py
1 input = open("hours.txt")
2 for line in input:
3 id, name, mon, tue, wed, thu, fri = line.split()
4
5 # cumulative sum of this employee's hours
6 hours = float(mon) + float(tue) + float(wed) + \
7 float(thu) + float(fri)
8
9 print(name, "ID", id, "worked", \
10 hours, "hours: ", hours/5, "/ day"
10
Writing Files
name = open("filename", "w")
name = open("filename", "a")
– opens file for write (deletes previous contents), or
– opens file for append (new data goes after previous data)
11
Exercise
• Write code to read a file of gas prices in USA and Belgium:
8.20 3.81 3/21/11
8.08 3.84 3/28/11
8.38 3.92 4/4/11
...
12