Python 07 Files
Python 07 Files
Chapter 7
Opening a File
• Before we can read the contents of the file, we must tell Python
which file we are going to work with and what we will be doing
with the file
• filename is a string
• Remember - a sequence is an
ordered set
Reading from a file
• You can also read a whole file #Counting the number of symbols
into one string using the read() fhand = open('mbox-short.txt')
inp=fhand.read()
function
print(len(inp))
• In this example the string inp
holds the entire file (newlines #Or we could print some symbols
and all) into a single string print(inp[:10])#first 10
Searching Through a File
fhand = open('mbox-short.txt')
We can conveniently for line in fhand:
skip a line by using the line = line.rstrip()
if not line.startswith('From:') :
continue statement continue
print(line)
Using in to Select Lines
fhand = open('mbox-short.txt')
We can look for a string for line in fhand:
anywhere in a line as our line = line.rstrip()
if not '@uct.ac.za' in line :
selection criteria continue
print(line)
Names exit()
count = 0
for line in fhand:
if line.startswith('Subject:') :
count = count + 1
print('There were', count, 'subject lines in', fname)
• Create a new file that contains any combination of: whitespaces, newlines,
and tabs. Write a program that prints the content of the file (by printing ‘\t’
instead of a blank space representing a tab, and ‘\n’ for a newline), then
output the number of letters in the file, and also the number of ‘tabs’.