Pythonlearn 07 Files
Pythonlearn 07 Files
Software What
It is time to go find some
Next? Data to mess with!
Input Central
and Output Processing Files R
Devices Unit Us
1 2
Details: http://source.sakaiproject.org/viewsvn/?view=rev&rev=39772
• open() returns a “file handle” - a variable used to perform
operations on the file
http://www.py4e.com/code/mbox-short.txt
• Similar to “File -> Open” in a Word Processor
3 4
10/01/21
• filename is a string
5 6
7 8
10/01/21
From [email protected] Sat Jan 5 09:14:16 2008 From [email protected] Sat Jan 5 09:14:16 2008\n
Return-Path: <[email protected]> Return-Path: <[email protected]>\n
Date: Sat, 5 Jan 2008 09:12:18 -0500 Date: Sat, 5 Jan 2008 09:12:18 -0500\n
To: [email protected] To: [email protected]\n
From: [email protected] From: [email protected]\n
Subject: [sakai] svn commit: r39772 - content/branches/ Subject: [sakai] svn commit: r39772 - content/branches/\n
\n
Details: http://source.sakaiproject.org/viewsvn/?view=rev&rev=39772 Details: http://source.sakaiproject.org/viewsvn/?view=rev&rev=39772\n
9 10
• Remember - a sequence is an
ordered set
11 12
10/01/21
13 14
From: [email protected]
...
15 16
10/01/21
17 18
19 20
10/01/21
Prompt for
fname = input('Enter the file name: ') fname = input('Enter the file name: ')
try:
Bad File
fhand = open(fname)
count = 0 fhand = open(fname)
File Name
for line in fhand: except:
print('File cannot be opened:', fname)
Names
if line.startswith('Subject:') :
count = count + 1 quit()
print('There were', count, 'subject lines in', fname)
count = 0
for line in fhand:
if line.startswith('Subject:') :
count = count + 1
print('There were', count, 'subject lines in', fname)
Enter the file name: mbox.txt
There were 1797 subject lines in mbox.txt
Enter the file name: mbox.txt
Enter the file name: mbox-short.txt There were 1797 subject lines in mbox.txt
There were 27 subject lines in mbox-short.txt
Enter the file name: na na boo boo
File cannot be opened: na na boo boo
21 22
• File structure - newline character • Dealing with bad files Initial Development: Charles Severance, University of Michigan
School of Information
23 24