W07 Files
W07 Files
W07 Files
0 1 1 0 0 0 1 1 0 1 1 0 0 0 0 1 0 1 1 1 0 1 0 0
0 1 1 0 0 0 1 1 0 1 1 0 0 0 0 1 0 1 1 1 0 1 0 0
0 1 1 0 0 0 1 1 0 1 1 0 0 0 0 1 0 1 1 1 0 1 0 0
C a t
47
Files and Filenames
• A file object represents data on your disk drive
– Can read from it and write to it
• A filename (usually a string) states where to find the data
on your disk drive
– Can be used to find/create a file
• Each operating system comes with its own file system for
creating and accessing files:
– Linux/Mac: "/home/volkan/seng113/lectures/W06-files.pptx "
– Windows: "C:\Users\volkan\MyDocuments\W06-Files.pptx "
48
Two Types of Filenames
• An Absolute filename gives a specific location on disk:
" /home/volkan/seng113/lectures/W06-files.pptx " or
"C:\Users\volkan\MyDocuments\homework3\images\Husky.png "
– Starts with “/” (Unix) or “C:\” (Windows)
– Warning: code will fail to find the file if you move/rename files or
run your program on a different computer
• A Relative filename gives a location relative to the current
working directory:
"lectures/file_io.pptx " or "images\Husky.png "
– Warning: code will fail to find the file unless you run your program
from a directory that contains the given contents
49
Examples
Linux/Mac: These could all refer to the same file:
"/home/volkan/class/140/homework3/images/Husky.png"
"homework3/images/Husky.png"
"images/Husky.png"
"Husky.png"
50
Locating files: the os module
>>> import os
>>> cwd = os.getcwd()
>>> cwd
'/Users/r2d2/'
>>> os.listdir()
['death_star_plans', 'princess_leia']
>>> os.listdir('princess_leia')
['Obi-Wan.txt', 'Anakin.txt']
>>> os.chdir('princess_leia')
>>> cwd
'/Users/r2d2/princess_leia'
51
Locating files: the os module
>>> import os os module lets us interact with the operating system.
>>> cwd = os.getcwd() https://docs.python.org/3.6/library/os.html
>>> cwd
'/Users/r2d2/'
>>> os.listdir()
['death_star_plans', 'princess_leia']
>>> os.listdir('princess_leia')
['Obi-Wan.txt', 'Anakin.txt']
>>> os.chdir('princess_leia')
>>> cwd
'/Users/r2d2/princess_leia'
52
Locating files: the os module
>>> import os os module lets us interact with the operating system.
>>> cwd = os.getcwd() https://docs.python.org/3.6/library/os.html
>>> cwd
'/Users/r2d2/' os.getcwd() returns a string
corresponding to the current working
>>> os.listdir() directory.
['death_star_plans', 'princess_leia']
>>> os.listdir('princess_leia')
['Obi-Wan.txt', 'Anakin.txt']
>>> os.chdir('princess_leia')
>>> cwd
'/Users/r2d2/princess_leia'
53
Locating files: the os module
>>> import os os module lets us interact with the operating system.
>>> cwd = os.getcwd() https://docs.python.org/3.6/library/os.html
>>> cwd
'/Users/r2d2/' os.getcwd() returns a string
corresponding to the current working
>>> os.listdir() directory.
['death_star_plans', 'princess_leia']
os.listdir() lists the
contents of its argument, or the
>>> os.listdir('princess_leia')
current directory if no argument.
['Obi-Wan.txt', 'Anakin.txt']
>>> os.chdir('princess_leia')
>>> cwd
'/Users/r2d2/princess_leia'
54
Locating files: the os module
>>> import os os module lets us interact with the operating system.
>>> cwd = os.getcwd() https://docs.python.org/3.6/library/os.html
>>> cwd
'/Users/r2d2/' os.getcwd() returns a string
corresponding to the current working
>>> os.listdir() directory.
['death_star_plans', 'princess_leia']
os.listdir() lists the
contents of its argument, or the
>>> os.listdir('princess_leia')
current directory if no argument.
['Obi-Wan.txt', 'Anakin.txt']
55
Locating files: the os module
>>> import os
>>> cwd = os.getcwd()
>>> cwd
'/Users/r2d2/'
>>> os.listdir()
['death_star_plans', 'princess_leia']
>>> os.listdir('princess_leia')
['c3po', 'Obi-Wan.txt', 'Anakin.txt']
>>> os.path.abspath('princess_leia/Obi-Wan.txt')
'/Users/r2d2/princess_leia/Obi-Wan.txt'
56
Locating files: the os module
>>> import os
>>> cwd = os.getcwd()
>>> cwd
'/Users/r2d2/'
>>> os.listdir()
['death_star_plans', 'princess_leia']
>>> os.path.abspath('princess_leia/Obi-Wan.txt')
'/Users/r2d2/princess_leia/Obi-Wan.txt'
57
Locating files: the os module
>>> import os
>>> os.chdir('/Users/r2d2')
>>> os.listdir('princess_leia')
['c3po', 'Obi-Wan.txt', 'Anakin.txt']
>>> os.path.exists('princess_leia/Anakin.txt')
True
>>> os.path.exists('princess_leia/JarJarBinks.txt')
False
>>> os.path.isdir('princess_leia/c3po')
True
>>> os.path.isdir('princess_leia/Obi-Wan.txt’)
False
58
Locating files: the os module
>>> import os
>>> os.chdir('/Users/r2d2')
>>> os.listdir('princess_leia')
['c3po', 'Obi-Wan.txt', 'Anakin.txt']
>>> os.path.exists('princess_leia/Anakin.txt')
True
Check whether or not a file/directory exists.
>>> os.path.exists('princess_leia/JarJarBinks.txt')
False
>>> os.path.isdir('princess_leia/c3po')
True
>>> os.path.isdir('princess_leia/Obi-Wan.txt’)
False
59
Locating files: the os module
>>> import os
>>> os.chdir('/Users/r2d2')
>>> os.listdir('princess_leia')
['c3po', 'Obi-Wan.txt', 'Anakin.txt']
>>> os.path.exists('princess_leia/Anakin.txt')
True
Check whether or not a file/directory exists.
>>> os.path.exists('princess_leia/JarJarBinks.txt')
False
>>> os.path.isdir('princess_leia/c3po')
True
Check whether or not this is a directory.
os.path.isfile() works analogously
>>> os.path.isdir('princess_leia/Obi-Wan.txt’)
False
60
Reading files
volkan:~/demo$ cat demo.txt
This is a demo file.
It is a text file, containing three lines of text.
Here is the third line.
volkan:~/demo$
>>> f = open('demo.txt')
>>> type(f)
<type 'file'>
>>> f.readline()
'This is a demo file.\n'
61
Reading files
volkan:~/demo$ cat demo.txt
This is a demo file.
It is a text file, containing three lines of text.
Here is the third line.
volkan:~/demo$
>>> f = open('demo.txt')
>>> type(f)
Open the file demo.txt . This creates a file object f
<type 'file'>
https://docs.python.org/3/glossary.html#term-file-object
>>> f.readline()
'This is a demo file.\n'
63
Reading files
volkan:~/demo$ cat demo.txt
This is a demo file.
It is a text file, containing three lines of text.
Here is the third line.
volkan:~/demo$
>>> f = open('demo.txt')
>>> type(f)
Open the file demo.txt . This creates a file object f
<type 'file'>
https://docs.python.org/3/glossary.html#term-file-object
64
Reading files
volkan:~/demo$ cat demo.txt
This is a demo file.
It is a text file, containing three lines of text.
Here is the third line.
volkan:~/demo$
>>> f = open('demo.txt')
>>> f.readline()
'This is a demo file.\n'
>>> f.readline()
'It is a text file, containing three lines of text.\n'
>>> f.readline()
'Here is the third line.\n'
>>> f.readline()
65
Reading files
volkan:~/demo$ cat demo.txt
This is a demo file.
It is a text file, containing three lines of text.
Here is the third line.
volkan:~/demo$
>>> f = open('demo.txt')
>>> f.readline()
Each time we call f.readline() ,
'This is a demo file.\n' we get the next line of the file...
>>> f.readline()
'It is a text file, containing three lines of text.\n'
>>> f.readline()
'Here is the third line.\n'
>>> f.readline()
66
Reading files
volkan:~/demo$ cat demo.txt
This is a demo file.
It is a text file, containing three lines of text.
Here is the third line.
volkan:~/demo$
>>> f = open('demo.txt')
>>> f.readline()
Each time we call f.readline() ,
'This is a demo file.\n' we get the next line of the file...
>>> f.readline()
'It is a text file, containing three lines of text.\n'
>>> f.readline()
'Here is the third line.\n'
>>> f.readline()
...until there are no more lines to read, at
which point the readline() method returns
the empty string whenever it is called 67
Reading files
>>> f = open('demo.txt')
>>> for line in f:
... for wd in line.split():
... print(wd.strip('.,'))
This
is
a
demo
file
It
is
a
text
file
containing
three
lines
of
text
Here
is
the
third
line
68
Reading files We can treat f as an iterator, in which
>>> f = open('demo.txt') each iteration gives us a line of the file.
>>> for line in f:
... for wd in line.split():
... print(wd.strip('.,'))
This
is
a
demo
file
It
is
a
text
file
containing
three
lines
of
text
Here
is
the
third
line
69
Reading files We can treat f as an iterator, in which
>>> f = open('demo.txt') each iteration gives us a line of the file.
>>> for line in f:
... for wd in line.split():
... print(wd.strip('.,')) Iterate over each word in the line
This (splitting on '' by default).
is
a
demo
file
It
is
a
text
file
containing
three
lines
of
text
Here
is
the
third
line
70
Reading files We can treat f as an iterator, in which
>>> f = open('demo.txt') each iteration gives us a line of the file.
>>> for line in f:
... for wd in line.split():
... print(wd.strip('.,')) Iterate over each word in the line
This (splitting on '' by default).
is
a
demo Remove the trailing punctuation
file from the words of the file.
It
is
a
text
file
containing
three
lines
of
text
Here
is
the
third
line
71
Reading files We can treat f as an iterator, in which
>>> f = open('demo.txt') each iteration gives us a line of the file.
>>> for line in f:
... for wd in line.split():
... print(wd.strip('.,')) Iterate over each word in the line
This (splitting on '' by default).
is
a
demo Remove the trailing punctuation
file from the words of the file.
It
is
a
text
file
containing
open() provides a bunch more (optional) arguments,
three
lines some of which we’ll discuss later.
of https://docs.python.org/3/library/functions.html#open
text
Here
is
the
third
line
72
Reading files
>>> with open('demo.txt’) as f:
... for line in f:
... for wd in line.split():
... print(wd.strip('.,'))
This
is
a
demo
file
It
is
a
text
file
containing
three
lines
of
text
Here
is
the
third
line
73
Reading files
>>> with open('demo.txt’) as f:
... for line in f:
You may often see code written
... for wd in line.split():
... print(wd.strip('.,'))
this way, using the with keyword.
This
It suffices to know that this is
is equivalent to what we did on the
a previous slide.
demo
file
It
is
a
text
file
containing
three
lines
of
text
Here
is
the
third
line
74
Reading files
>>> with open('demo.txt’) as f:
... for line in f:
You may often see code written
... for wd in line.split():
... print(wd.strip('.,'))
this way, using the with keyword.
This
It suffices to know that this is
is equivalent to what we did on the
a previous slide.
demo
file
It
is From the documentation: “It is good practice to use the with
a keyword when dealing with file objects. The advantage is that the
text file is properly closed after its suite finishes, even if an exception is
file
containing raised at some point.”
three https://docs.python.org/3/reference/compound_stmts.html#with
lines
of
text In plain English: the with keyword does a bunch of error
Here checking and cleanup for you, automatically.
is
the
third
line
75
Reading a File Example
# Count the number of words in a text file
in_file = "thesis.txt"
myfile = open(in_file)
num_words = 0
for line_of_text in myfile:
word_list = line_of_text.split()
num_words += len(word_list)
myfile.close()
76
Reading a File Multiple Times
You can iterate over a list as many times as How to read a file multiple times?
you like:
mylist = [ 3, 1, 4, 1, 5, 9 ]
Solution 1: Read into a list, then iterate over it
for elt in mylist: myfile = open("datafile.dat")
mylines = []
… process elt
for line_of_text in myfile:
for elt in mylist: mylines.append(line_of_text)
… process elt … use mylines
>>> f.write('cat\n')
>>> f.write('dog\n')
>>> f.write('bird\n')
>>> f.write('goat\n')
78
Open the file in write mode.
Writing files If the file already exists, this
creates it anew, deleting its
old contents.
>>> f = open('animals.txt', 'w')
>>> f.read()
>>> f.write('cat\n')
>>> f.write('dog\n')
>>> f.write('bird\n')
>>> f.write('goat\n')
79
Open the file in write mode.
Writing files If the file already exists, this
creates it anew, deleting its
old contents.
>>> f = open('animals.txt', 'w')
>>> f.read() If I try to read a file in write mode, I get an error.
>>> f.write('cat\n')
>>> f.write('dog\n')
>>> f.write('bird\n')
>>> f.write('goat\n')
80
Open the file in write mode.
Writing files If the file already exists, this
creates it anew, deleting its
old contents.
>>> f = open('animals.txt', 'w')
>>> f.read() If I try to read a file in write mode, I get an error.
81
Writing files
>>> f = open('animals.txt', 'w')
>>> f.write('cat\n')
>>> f.write('dog\n')
>>> f.write('bird\n')
>>> f.write('goat\n')
>>> f.close()
82
Open the file in write mode.
Writing files This overwrites the version of
the file created in the previous
slide.
>>> f = open('animals.txt', 'w')
>>> f.write('cat\n')
>>> f.write('dog\n')
>>> f.write('bird\n')
>>> f.write('goat\n')
>>> f.close()
83
Open the file in write mode.
Writing files This overwrites the version of
the file created in the previous
slide.
>>> f = open('animals.txt', 'w')
>>> f.write('cat\n')
>>> f.write('dog\n')
Each write appends to the end of the file.
>>> f.write('bird\n')
>>> f.write('goat\n')
>>> f.close()
84
Open the file in write mode.
Writing files This overwrites the version of
the file created in the previous
slide.
>>> f = open('animals.txt', 'w')
>>> f.write('cat\n')
>>> f.write('dog\n')
Each write appends to the end of the file.
>>> f.write('bird\n')
>>> f.write('goat\n') When we’re done, we close the file. This
happens automatically when the program
>>> f.close() ends, but its good practice to close the file
as soon as you’re done.
>>> f = open('animals.txt', 'r')
>>> for line in f:
... print(line, end=’’)
cat
dog
bird
goat
85
Open the file in write mode.
Writing files This overwrites the version of
the file created in the previous
slide.
>>> f = open('animals.txt', 'w')
>>> f.write('cat\n')
>>> f.write('dog\n')
Each write appends to the end of the file.
>>> f.write('bird\n')
>>> f.write('goat\n') When we’re done, we close the file. This
happens automatically when the program
>>> f.close() ends, but its good practice to close the file
as soon as you’re done.
>>> f = open('animals.txt', 'r')
>>> for line in f: Now, when I open the file for reading,
... print(line, end=’’) I can print out the lines one by one.
cat
dog
bird
goat
86
Open the file in write mode.
Writing files This overwrites the version of
the file created in the previous
slide.
>>> f = open('animals.txt', 'w')
>>> f.write('cat\n')
>>> f.write('dog\n')
Each write appends to the end of the file.
>>> f.write('bird\n')
>>> f.write('goat\n') When we’re done, we close the file. This
happens automatically when the program
>>> f.close() ends, but its good practice to close the file
as soon as you’re done.
>>> f = open('animals.txt', 'r')
>>> for line in f: Now, when I open the file for reading,
... print(line, end='') I can print out the lines one by one.
cat
dog The lines of the file already include newlines
on the ends, so override Python’s default
bird
behavior of printing a newline after each line.
goat
87
More Examples - 1
nameHandle = open('characters.txt', 'w')
for i in range(2):
name = input('Enter name: ')
nameHandle.write(name + '\n')
nameHandle.close()
• If we had typed in the names Rick and Morty, this will print
Rick
Morty
• The extra line between Rick and Morty is there because print starts a new line
each time it encounters the '\n' at the end of each line in the file.
88
More Examples - 2
nameHandle = open('characters.txt', 'w')
nameHandle.write('Jerry\n')
nameHandle.write('Beth\n')
nameHandle.close()
• It will print
Jerry
Beth
• Notice that
• we have overwritten the previous contents of the file.
• print line[:-1] avoids extra newline in the output
89
More Examples - 3
nameHandle = open('characters.txt', 'a')
nameHandle.write('Rick\n')
nameHandle.write('Morty\n')
nameHandle.close()
• It will print
Jerry
Beth
Rick
Morty
• Notice that we can open the file for appending (instead of writing) by using
the argument 'a' .
90
Common functions for accessing files
• open(fn, 'w') fn is a string representing a file name. Creates
a file for writing and returns a file handle.
• open(fn, 'r') fn is a string representing a file name. Opens
an existing file for reading and returns a file handle.
• open(fn, 'a') fnis a string representing a file name. Opens
an existing file for appending and returns a file handle.
• fn.close() closes the file associated with the file handle fn .
91
Common functions for accessing files
• fn.read() returns a string containing the contents of the file
associated with the file handle fn .
• fn.readline() returns the next line in the file associated with
the file handle fn .
• fn.readlines() returns a list each element of which is one
line of the file associated with the file handle fn .
• fn.write(s) write the string s to the end of the file associated
with the file handle fn .
• fn.writelines(S) S is a sequence of strings. Writes each
element of S to the file associated with the file handle fn .
92
Formatting Strings
>>> x = 23
>>> print(‘x = %d' % x)
x = 23
93
Formatting Strings
Python provides tools for formatting
>>> x = 23 strings. Example: easier way to print
>>> print(‘x = %d' % x) an integer as a string.
x = 23
94
Formatting Strings
Python provides tools for formatting
>>> x = 23 strings. Example: easier way to print
>>> print(‘x = %d' % x) an integer as a string.
x = 23
%d: integer
%s: string
>>> animal = 'unicorn' %f: floating point
>>> print('My pet %s' % animal) More information:
My pet unicorn https://docs.python.org/3/library/stdtypes.
html#printf-style-string-formatting
>>> x=2.718; y=1.618
>>> print('%f divided by %f is %f' % (x,y,x/y))
2.718000 divided by 1.618000 is 1.679852
95
Formatting Strings
Python provides tools for formatting
>>> x = 23 strings. Example: easier way to print
>>> print(‘x = %d' % x) an integer as a string.
x = 23
%d: integer
%s: string
>>> animal = 'unicorn' %f: floating point
>>> print('My pet %s' % animal) More information:
My pet unicorn https://docs.python.org/3/library/stdtypes.
html#printf-style-string-formatting
>>> x=2.718; y=1.618
>>> print('%f divided by %f is %f' % (x,y,x/y)) Can further control details of
2.718000 divided by 1.618000 is 1.679852 formatting, such as number of
significant figures in printing floats.
96
Formatting Strings
Python provides tools for formatting
>>> x = 23 strings. Example: easier way to print
>>> print(‘x = %d' % x) an integer as a string.
x = 23
%d: integer
%s: string
>>> animal = 'unicorn' %f: floating point
>>> print('My pet %s' % animal) More information:
My pet unicorn https://docs.python.org/3/library/stdtypes.
html#printf-style-string-formatting
>>> x=2.718; y=1.618
>>> print('%f divided by %f is %f' % (x,y,x/y)) Can further control details of
2.718000 divided by 1.618000 is 1.679852 formatting, such as number of
significant figures in printing floats.
98