55284A - Introduction To Python - Chapter10
55284A - Introduction To Python - Chapter10
Topics Covered
Reading files.
Creating
Th and writing to files.
is
do
cu
me
Working with directories.
nt
be
lon
ja
Working with Nthe osgand gs
ou tap [Link] to modules.
na n i NI
uth lk a L K
ori nt@ ANT
ze re d ES
dc
op [Link] HWA
He made haste to sit down iniehis s a easym chair
R and opened the book. He tried to read, but he could not revive
JA
llo GT
the very vivid interest he had felt before we in Egyptian
AP hieroglyphics.
d! .
– Anna Karenina, Leo Tolstoy
Introduction
Th
is
d
Python allows youocto
umaccess and modify files and directories on the operating system. Among other things, you
en
can: tb
elo
n
No agta gs to
j
u na filesp n NIstore them in file object variables.
1. Open new or existing uth ilkaand LK
ori n t@ ANT
ze red E
2. Read file contents, all at once d c or iff. bySH
op line line.
WA
ies om c
R
all JA
ow GT
3. Append to file contents. ed AP
! .
4. Overwrite file contents.
open(path_to_file, file_mode)
path_to_file can either be a relative or an absolute path. File modes are described in the following list:
Th
is
do
1. "r" – Open for cu reading (default). Returns FileNotFoundError if the file doesn’t exist.
me
nt
be
lon
2. "w" – Open for N writing.
ja g Ifgsthe file exists, existing content is erased. If the file doesn’t exist, a new file is
created.
3. "x" – Create and open for writing. Returns FileExistsError if the file already exists.
4. "a" – Open for appending to end of content. If the file doesn’t exist, a new file is created.
5. "a+" – Open for appending to end of content and reading. If the file doesn’t exist, a new file is created.
6. "r+" –TOpen
his for reading and writing.
do
cu
7. "w+" – Open for mewriting and reading. If the file exists, existing content is erased. If the file doesn’t exist, a new
nt
be
file is created. lon
No ja gta gs to
un pn NI
8. "b" – Opens in binary au mode. il LK
tho kant
riz @ ANT
ed red ES
co is HW
if . default.
9. "t" – Opens in text mode. This pie fthe co AR
sa m JA
llo GT
we AP
d! .
[Link](size) – reads size bytes of the file. If size is omitted, the entire file is read.
[Link]() – reads a single line up to and including the newline character (\n).
[Link]()
Th – reads the file into a list split after the newline characters. Each line will end with a newline
is
character. doc
um
en
tb
[Link]().splitlines() elo – reads the file into a string and then splits on the newline characters. Lines will
N jag ngs
not end with newline
ou tcharacters.
a to
na pnilk NIL
uth a K
ori nt@ ANT
list(f) – does the same ze thingr as [Link]().
d c ediff ESH
op . WA
ies com R
all JA
ow GT
ed AP
! .
Closing Files
You should always be sure to close files when you are done with them. This can be done with the [Link]()
method like this:
Th
is
do
f = open('my_files/zen_of_python.txt')
c um
en
# Do stuff with filet be
lo
[Link]()
N jag ngs
While this works, it creates a potential problem. What if an exception occurs between the time the file is opened
and closed? We will be left with a dangling reference to the file holding onto system resources and potentially
blocking other applications from accessing the file.
As we have seen (see page 27), a better practice is to use the with keyword when working with files, like this:
Th
is
do
with open(file)cum
as f:
en
tb
do_stuff() elo
n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
r
Using this structure, we don’t izhave T close the file with [Link](). File objects have a special built-in
ed toreexplicitly
dif ESH
__exit__() method that closes the c f
op [Link] W called at the end of a with block even if code within the
ies om always is AR
with block raises an exception. Often, you a J A
llo will read aGfile into a variable within a with block and then use the
we TA
variable throughout the script, as shown in the d! following demo:
P.
1. with open('my_files/zen_of_python.txt') as f:
Th
i
s d = [Link]()
2. poem o cu
men
3. tb
e
4. # The file is janowlonclosed, but we saved its content in the poem variable
No gta gs to
5. for i, line uin pn NI
na enumerate([Link](), 1):
il u L ka K
th n A
6. riz t@re NTE
print(f"{i}. o{line}")
ed d S H
co if
pie [Link] WAR
sa JA
llo GT
we AP
Code Explanation d! .
Th
python [Link]
is
do
cu
men
tb
This will output: elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
1. The Zen of Python co diff.c H
pie om WAR
2. Tim Peters s all JA
ow GT
3. [Link] e d! AP
.
4.
5. Beautiful is better than ugly.
6. Explicit is better than implicit.
7. Simple is better than complex.
This better than complicated.
8. Complex is
do
9. Flat is bettercu than nested.
m en
t b than dense.
10. Sparse is better e lo
jag ngs
11. ReadabilityN counts.
12. Special cases aren't special enough to break the rules.
13. Although practicality beats purity.
14. Errors should never pass silently.
15. Unless explicitly silenced.
16. In the face of ambiguity, refuse the temptation to guess.
17. There should be one-- and preferably only one --obvious way to do it.
18. Although that way may not be obvious at first unless you're Dutch.
hsT
19. Now is ibetter
do than never.
cu
m
20. Although neveren is often better than *right* now.
tb
e
lon is hard to explain, it's a bad idea.
21. If the implementation
No jagta gs to
un
22. If the implementation p isNIeasy to explain, it may be a good idea.
au nilka LK
t h o
23. Namespaces are one rihonkingn t@ A NT
great idea -- let's do more of those!
ze
d c rediff ESH
op . WA
ies com R
all JA
ow GT
ed AP
! .
T15
his
to 25 minutes
do
cu
me
nt
be
In this exercise, you will create lon a tool for searching through a file. This is the starting code:
No agta gs to
j
un p NI
au nilka L
tho nt@ KAN
Exercise Code: file-processing/Exercises/word_search.py
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
1. def search(word, text): llo GT
we AP
d! .
2. """Return tuple holding line num and line text (or None)."""
3. pass
4.
5. def main():
6. # Open my_files/zen_of_python.txt and
T
7. # hicreate
sd a list from its contents
oc
8. # Saveum
the
e list as zop
nt
be
9. lon
No jagta gs to
10. word = input('Enter
un p NIsearch word: ')
au nilka L
11. tho
result = search(word, nt@ KAzop) N
riz red TES
ed H
co if
pie [Link] WAR
12. if result:
13. s
print(word, ' firstall appears on JA line ',
ow GT
result[0], ': ', dresult[1],e APsep='')
14. ! .
15. else:
16. print(word, 'was not found.')
17.
18. main()
Th
is
do
cu
men
tb
elo
1. ja ng
Open file-processing/Exercises/word_search.py in your editor.
N g s
2. In the main() function, open my_files/zen_of_python.txt and create a list from its contents. Save the
list as zop.
3. The rest of the main() function is already written. Read through the code to make sure you understand what
it is doing.
4. Replace pass in the search() function with code that returns a two-element tuple containing the line
number and line text in which the passed-in word is found. Return None if the word is not found. You may find
Th
is review the enumerate() function (see page 196).
it useful to do
cu
me
nt
5. Run your solution by beopening the terminal at file-processing/Exercises and running:
lon
No ja gta gs to
un p NI
au nilka L
python word_search.py tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .
Challenge
Modify the code so that it prints all the lines in which the word is found, like this:
Th
is
do
cu
Enter search word:
m than en
t b 5: Beautiful is better than ugly.
than appears on line elo
jag 6:ngExplicit
than appears onNoline st
ta o is better than implicit.
pn
un i NI
au 7: lSimple LK is better than complex.
than appears on line tho kant
riz @ ANT
ed
than appears on line 8: Complex red isEbetter
SH than complicated.
c if o f. W
p e com AR
than appears on line 9: Flat iis
s abetter thanJA nested.
llo GT
w
than appears on line 10: Sparse is ebetter APdense.
than
d ! .
than appears on line 19: Now is better than never.
than appears on line 20: Although never is often better than *right* now.
Th
is
Solution: file-processing/Solutions/word_search.py
do
cu
me
nt
be
1. def search(word, lotext):
n
No jagta gs to
2. u
"""Returnnatuple p N
n holding line num and line text."""
uth ilkan ILKA
3. ori
for line in enumerate(text, t@ NT 1):
ze
d c rediff ESH
op . W 0:
4. if line[1].find(word)
ies com >= A R
a llo JA
5. return line we GT
d! AP
6. return None .
7.
8. def main():
9. with open('my_files/zen_of_python.txt') as f:
10. zop = [Link]()
Th
11. is
do
c
12. word =um
input('Enter
e search word: ')
nt
elo b
13. result = search(word,
n zop)
N jag gs
14. if result:
15. print(word, ' first appears on line ',
16. result[0], ': ', result[1], sep='')
17. else:
18. print(word, 'was not found.')
19.
20. main()
Th
is
do
cu
men
tb
elo
Challenge Solution: jag ngs
No file-processing/Solutions/word_search_challenge.py
t t
un apni o NI
au l LK
tho kant
riz @ ANT
ed re ES
1. def search(word, text): co diff.c H
pie om WAR
2. """Return tuple holding s a line num JA
and line text."""
llo GT
we AP
3. results = [] d! .
4. for line in enumerate(text, 1):
5. if line[1].find(word) >= 0:
6. [Link](line)
7. return results
8. Th
is
oc d
9. def main():
um
en
10. tb
with open('my_files/zen_of_python.txt') as f:
e lon
11. zop gt gs
N = [Link]()
ou
ap t
oN
na n
12. uth ilkan ILKA
ori t NT
ze @rsearch
13. word = input('Enter d c ediff ESword: ')
op .co HWA
14. results = search(word, i es zop)m R
all JA
ow GT
15. if not results: ed AP
! .
16. print(word, 'was not found.')
17.
18. for result in results:
19. print(word, ' appears on line ', result[0],
20. Th ': ', result[1], sep='', end='')
is
21. do
cu
men
22. main() tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
Writing to Files co diff.c HW
pie o AR
sa m J
Files opened with a mode that permits writing l low can beAwritten
GT to using the write() method as shown in the
ed AP
following file: ! .
python simple_write.py
Th
is
do
3. Now, look againcu in the file-processing/Demos/my_files folder. It should now contain a [Link] file.
me
nt
be to see its contents.
Open it in a text editor lon
No ja gta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c WA
pie
Exercise 30: Writings to all
oFiles
m R
JA
ow GT
ed AP
! .
5 to 10 minutes
In this exercise,
Th you will learn how modes affect reading and writing files. This exercise starts out like the previous
is
demo. do
cu
me
nt
be
lon
1. Open file-processing/Exercises/simple_write.py in your editor.
No agta gs to
j
un pn
ilka NILK
2. Before running thisaufile, tho look n in theAfile-processing/Exercises/my_files folder. It should not contain
riz t@re NTE
a [Link] file. If it does, ed deleted it. SH
co if
pie [Link] WAR
sa JA
3. Now, run the file from file-processing/Exercises llo GT at the terminal:
we AP
d! .
python simple_write.py
4. Now, look again in the file-processing/Exercises/my_files folder. The [Link] file should be
Th
is it in a text editor to see its contents.
there. Open do
cu
me
nt
5. In simple_write.py, be change the string passed to the write() method to “Pass on what you have
lon
No jagtayougslike.
learned” or whatever to
un p NI
au nilka L
tho nt@ KAN
6. Run the file again. It shouldriz completely overwrite the file with the new string.
ed red TES
co if H
pie [Link] WAR
7. Now, change the mode from "w" s to
all "a" and run
JA it again. This time, it should append to the file.
ow GT
ed AP
8. Try adding a call to print([Link]()) on the line after! . the call to [Link]() and run the file again. You
should get an error. Review the modes at the beginning of this lesson (see page 262) to see if you can figure
out why and how to fix it.
Th
Challenge is
do
cu
en m
tb
The seek() method is used elo to change the cursor position in the file object. Its most common purpose is to
ja ng
N ofgthe file
return to the beginning s by passing it 0. If you were able to fix the issue causing the error when you added
the call to [Link](), you may have been surprised to find that the content you wrote to the file didn’t get read.
This is because, after writing, the cursor is at the end of the file. Use the seek() method to fix this so that the
contents of the file are printed out.
Solution: file-processing/Solutions/simple_write.py
1. with Topen('my_files/[Link]',
h 'a+') as f:
is
2. oc d
[Link]('Powerful you have become.')
u me
3. [Link](0)nt b
elo
4. jag ngs
print([Link]())
N tap
ou to
n na N
uth ilkan ILKA
ori t N
ze @red TES
dc iff HW
Code Explanation op .
ies com AR
all JA
ow GT
ed AP
!
Placing the cursor at the beginning of the file with [Link](0) . makes it possible to read the entire contents of the
file.
A. add_item(item)
Th
B. is
remove_item(item) – This one is a little tricky. You will need to open the file twice, once for reading
do
cu
and once m enwriting. You may also find the splitlines() method (see page 132) of a string object
for
tb
useful. elo
ja ng
N g s
C. delete_list()
D. print_list()
Th
is
Challenge do
cu
men
tb
elo
1. The delete_list() n
function currently deletes the list without warning. Give the user a chance to confirm
No agta gs to
j
u
before deleting the p
nalist. nilk N ILK
uth a
ori nt@ ANT
ze
2. In the print_list() function, d c reuse
d the ES
enumerate() function to print the items as a numbered list.
op [Link] HWA
ies m R
all JA
ow GT
ed AP
! .
Solution: file-processing/Solutions/list_creator.py
1. def add_item(item):
2. """Appends item (after stripping leading and trailing
3. Th
whitespace) to [Link] followed by newline character
is
do
4. cu
men
tb
5. el
Keyword arguments:
on
j
ag items to append"""
N the g
6. item --
7. with open('[Link]', 'a') as f:
8. [Link]([Link]() + '\n')
9.
10. def remove_item(item):
11. """Removes first instance of item from [Link]
12. If item is not found in [Link], alerts user.
13.
Th
is
14. do
Keyword arguments:
cu
15. item --mthe
en item to remove"""
tb
16.
e
item_found = loFalse
jagn gs
N
ou ap oNt t
17. with open('[Link]',
n n I 'r') as f:
au ilka LK
18. t ori nt@ ANT
items = [Link]().splitlines()
ze
d c rediff ESH
19. if item in items: op . WA
ies com R
20. [Link](item) all JA
ow GT
e AP
21. item_found = True d! .
22. else:
23. print('"' + item + '" not found in list.')
24.
25. if item_found:
Th
26. is with open('[Link]', 'w') as f:
do
cu
27. [Link]('\n'.join(items)
en + '\n')
tb
28. elo
N jag ngs
29. ou
def delete_list(): ta to
na pnilk NIL
30. """Deletes the u a
tho entire n KAcontents of the list by opening
riz t@re NTE
e d d SH
31. [Link] for writing.""" co if
pie [Link] WAR
32. with open('[Link]',s a'w') as f:JA
llo GT
we AP
33. print('The list has been d! deleted.')
.
34.
35. def print_list():
36. """Prints list"""
37. with open('[Link]', 'r') as f:
38. Th
is print([Link]())
do
cu 39 through 78 Omitted-------
-------Lines me
nt
be
lon
No jagta gs to
un p NI
au nilka LK
t h ori n t AN
Challenge Solution: file-processing/Solutions/list_creator_challenge.py
ze @red TES
dc
op [Link] HWA
ies m R
all JA
-------Lines 1 through 28 Omitted------- ow GT
ed AP
29. def delete_list():
! .
Th
[Link](path) is
do changes the current directory to path.
cu
me
nt
b
The following code shows ehow lo to get the current working directory with [Link](), then change it using
jag ngs
[Link](), andNthen o u get to to prove that it changed:
tapit again
N
na n
uth ilkan ILKA
ori t N
ze @red TES
dc iff HW
op .
>>> import os ies com AR
all JA
ow GT
>>> [Link]() ed AP
! .
'C:\\Webucator\\Python\\file-processing\\Demos'
>>> [Link]('..')
>>> [Link]()
Th
'C:\\Webucator\\Python\\file-processing'
is
do
cu
men
tb
elo
Notice the double backslash. nThat’s because the string is escaped. Remember that the backslash is used to
No agta gs to
j
escape characters (see un page pn70). For a backslash to be just a backslash, it needs to be escaped by putting another
au ilka NILK
backslash in front of it. t h ori n t AN
ze @red TES
dc
op [Link] HWA
ies m R
[Link](path) all JA
ow GT
ed AP
!
Returns a list of files and subdirectories in path, which defaults . to the current directory.
1. import os
Th
sd i
2. dir_contents
o = [Link]("my_files")
cu
en m
3. for item in dir_contents:
t
elo b
4. print(item)
ja ng
N g s
Code Explanation
This prints out a list of files and directories in the my_files directory:
This creates directory a using mkdir() and then makes directories b and c using makedirs(). It then writes text
files to the a and b directories. Run make_dirs.py from the file-processing/Demos directory and then look
to see that the directories were created:
Th
is
do
cu
men
tb
elo
jag ng
N s
Th
is
do
cu
men
tb
elo
[Link](path) andj [Link](path)
n
No agta gs to
un p NI
au nilka L
tho nt@ KAN
r
[Link](path) deletes ithe ze directory T
d c rediff ESH
at path. It errors if the directory is not empty or
o p . c WA
doesn’t exist. ies om R
all JA
ow GT
ed AP
! .
[Link](path) is like rmdir(), but removes all empty directories in path, starting with the leaf (the last
directory in the path). It will error if the leaf directory is not empty.
[Link](path) and [Link](path) are identical. They delete the file at path, and they error if path
doesn’t point to a file.
Th
is
do
cu
1. Open the Python meterminal at file-processing/Demos if it’s not already open.
nt
be
lo
2. Run import Nos. jag ngs
ou tap to
na n N
uth ilkan ILKA
3. Run [Link]('my_files/a/b')
ori t N to show that directory b contains a file:
ze @red TES
dc iff. H
op WA
ies com R
all JA
>>> import os ow GT
ed AP
! .
>>> [Link]('my_files/a/b')
['[Link]']
Th
is
oc d
>>> [Link]('my_files/a/[Link]')
u me
nt
be
lon
No ja gta gs to
un p N
6. au nilkaa andILb
Now that both directories are empty, you can run [Link]('my_files/a/b') to remove
tho nt@ KAN
both directories, and then riz use [Link]('my_files')
re TE to check that they have been removed:
ed SH
co diff.c W
pie o AR
sa m JA
llo GT
>>> [Link]('my_files/a/[Link]') we AP
d! .
>>> [Link]('my_files/a/b')
>>> [Link]('my_files')
['a b [Link]', 'd e [Link]', '[Link]', 'g h [Link]', '[Link]',
'zen_of_python.txt']
Th
is
do
cu
7. Close the Python me terminal.
nt
be
lon
No agta gs to
j
un p NI
au nilka L
tho
[Link](source, destination) nt@ KANand [Link](oldpath, newpath)
riz re TE
ed SH
co diff.c
[Link](source, destination) pie om WARa file or a directory, changing the name from source to
renames
sa JA
destination. llo GT
we AP
d! .
[Link](oldpath, newpath) is like rename(source, destination), but it starts by creating all necessary
directories in newpath and ends by removing all empty directories in oldpath.
1. Before running this file, look in the file-processing/Demos/my_files folder. It should contain a file
named [Link].
2. Look in the file-processing/Demos folder. It should not contain a my_new_files folder. If it does,
delete it.
Th
is
do
3. cu
Now, run [Link] from the file-processing/Demos directory:
me
nt
be
lon
No ja gta gs to
PS …\file-processing\Demos>
un p NI python [Link]
au nilka LK
t ho n A
Renamed my_files/[Link] riz t@reto Nmy_new_files/[Link]
TE
ed
co d iff. SHW
pie com AR
sa JA
llo GT
4. Look again in the file-processing/Demos wed AP A my_new_files folder should have appeared. Open
folder.
! .
it to find a [Link] file, which is the [Link] renamed and moved.
5. Look again in the file-processing/Demos/my_files folder. The [Link] file should be gone. The
my_files folder remains, because it has other things in it.
6. Th
Open file-processing/Demos/[Link] in your editor. Change it so that it calls bar2foo()
is
do
instead of foo2bar().
cu Run the file again. The results:
me
nt
be
lon
A. file-processing/Demos/my_files/[Link] returns.
No agta gs to
j
un p NI
au nilka L
B. file-processing/Demos/my_new_files/[Link] gets deleted.
tho nt@ KAN
riz r e T E
ed SH
co diff.c
C. file-processing/Demos/my_new_files pie om WAR also gets deleted as the only file it contained was
sa J A
[Link]. llo GT
we AP
d! .
Walking a Directory
[Link](top,
T topdown=True, onerror=None, followlinks=False)
his
do
cu
en m
tb
The [Link]() method returns elo
n a generator by walking the directory tree and yielding a three-element tuple for
No agta gs to
j
each directory containing:
un p NI
au nilka L
tho nt@ KAN
riz red TES
e
dirpath – The path to thed cdirectory
op [Link] HaWstring.
ies m AR
all JA
dirnames – A list of subdirectories oinwedirpath. GTA
d! P.
filenames – A list of files in dirpath.
[Link]() Parameters
Th
is
do
cu
top – The top-level
me directory for the walk.
nt
be
lon
topdown – By default,
ja [Link]()
gs starts with top and works its way down; however, if topdown is False, it will
N g
work its way from bottom to top.
onerror – By default, errors are ignored. If you want to handle errors in some way, set^onerror to a function.
When an error occurs, that function will be called and passed an OSError instance.
Afollowlinks – By default, [Link]() ignores symbolic links (files that link to other directories). Set
followlinks to True to include those linked directories. Be careful: you could end up with an infinite loop!
Th
is
do
cu
Let’s take a look at anmeexample. Review the following code to see if you can understand what it does:
nt
be
lon
No ja gta gs to
Demo 78: file-processing/Demos/[Link]
un p NI
au nilka L
tho nt@ KAN
riz red TES
ed
1. import os
c op [Link] HWA
ies m R
all JA
2. ow GT
ed AP
3. def spaces2dashes(): ! .
3. Now, look again in the file-processing/Demos/my_files folder. The spaces in those file names should
have been replaced with dashes.
Th
4. is edit the file so that it runs dashes2spaces() in place of spaces2dashes() and run it again to
If you like, do
c
put the spacesum back
en in the file names.
tb
elo
ja ng
N g s
The [Link] Module
The [Link] module is used for performing functions on path names. In this section, we cover some of its most
useful methods:
[Link](path)
Th
is
oc d
[Link](path)
u returns the absolute path of path.
me
nt
be
lon
No ja gta gs to
un p NI
au nilka L
tho
>>> [Link]('.') nt@ KAN
riz re TE
ed SH
co diff.c
om WAR
'C:\\Webucator\\Python\\file-processing\\Demos'
pie
sa JA
llo GT
we AP
d! .
[Link](path)
T
his
[Link](path)
d returns the basename of path.
oc
um
en
tb
elo
n
No agta gs to
j
u na p n N
uth ilkan ILKA
>>> [Link]('my_files/[Link]')
ori t N
'[Link]' ze @red TES
dc iff HW
op .
ies com AR
all JA
ow GT
ed AP
! .
[Link](path)
[Link](path) returns the path to the directory containing the leaf element of path.
Th
is
do
cu
en m
>>> [Link]('my_files/[Link]')
tbe
'my_files' lon
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz r e TE
ed SH
co diff.c
pie om WAR
[Link](path) sa JA
llo GT
we AP
d! .
>>> [Link]('my_files/[Link]')
Th
is
True do
cu
m en
tb
elo
jag ng
N s
[Link](path),[Link](path),[Link](path)
[Link](path) returns the time path was last accessed in number of seconds from the epoch.
[Link](path) returns the time path was last modified in number of seconds from the epoch.
Th
is
do
um c
[Link](path)
e returns the time path was created in number of seconds from the
nt
epoch. be
lon
No ja gta gs to
un p NI
au nilka L
tho nt@ KAN
We can use the datetime moduler ize redconvertTE and format these as readable dates and times:
d c to iff
SH
op . WA
ies com R
all JA
ow GT
ed AP
!
>>> last_accessed = [Link]('my_files/[Link]')
.
[Link](path)
Th
[Link](path) returns the size of the file at path.
is
do
cu
m en
tb
elo
n
No agta gs to
j
>>> [Link]('my_files/[Link]')
un pn
au ilka NILK
26216 t h ori nt@ ANT
ze
d c rediff ESH
op . WA
ies com R
all JA
ow GT
ed AP
! .
[Link](path)
>>> [Link]('my_files/[Link]')
T his
False do
cu
m en
tb
elo
jag ng
N s
[Link](path, start)
[Link](path, start) returns a relative path to path from start, which defaults to the current
directory.
Th
>>> [Link](r'C:\Webucator\Python\file-processing\Demos\my_files\[Link]')
is
do
cu
m
'my_files\\[Link]'
en
tb
elo
n
No jagta gs to
u p NI
au “r”nprefix,
If you are confused by nthe il LK
review Raw Strings (see page 71).
tho kant
riz @ ANT
ed re ES
co diff.c HW
p
[Link](path) and [Link](path)
ies om AR
all JA
ow GT
ed AP
! .
[Link](path) returns True if path is a file.
>>> [Link]('my_files/[Link]')
Th
True is
do
cu
men
tb
elo
n
No agta gs to
j
un pn NI
[Link](path)aureturns il LK if path is a directory.
tho kant
True
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
>>> [Link]('my_files/[Link]') d ! .
False
[Link](path,
T *paths)
his
do
cu
en m
tb
[Link](path, *paths) elo returns a path by joining the passed-in paths intelligently. Note that different
N jag ngs
operating systems use tap path
o u different to structures. This will create the correct structure for the operating system it runs
na n N
on. uth ilkan ILKA
ori t N
ze @red TES
dc iff. HW
op
ies com AR
all JA
ow GT
>>> [Link]('my_files','[Link]') ed AP
! .
'my_files\\[Link]'
[Link](path)
Th
is
do tuple containing [Link](path) and [Link](path).
Returns a 2-element
cu
me
nt
be
lon
N ja g gs
>>> [Link]('my_files/[Link]')
('my_files', '[Link]')
[Link](path)
Th
is
do
Returns a 2-element cu tuple containing the path minus the extension and the extension.
me
nt
be
lon
No ja gta gs to
un p NI
au nilka
>>> [Link]('my_files/[Link]') L
tho nt@ KAN
r ize T
d c rediff ESH
('my_files/logo', '.png')
op . WA
ies com R
all JA
ow GT
ed AP
! .
A Better Way to Open Files
Let’s take another look at Demos/[Link]:
We previously ran that file from the file-processing/Demos directory and it worked just fine, but try running it
from a different directory:
1. Th
Open file-processing in the Python terminal.
is
do
cu
me
2. Run python Demos/[Link]:
nt
be
lon
No jagta gs to
un p NI
au nilka L
PS …\Python\file-processing>
tho nt@ KAN python Demos/[Link]
riz r TE
e last):
ed call SH
co diff.c
Traceback (most recent
p o W
File "Demos/[Link]", line i es 1, m in A<module>
R
all JA
ow GT
with open('my_files/zen_of_python.txt') ed AP as f:
! .
FileNotFoundError: [Errno 2] No such file or directory:
'my_files/zen_of_python.txt'
Th
is
The issue is thatdPython
oc
um is not looking for the file relative to where the Python file is; it is looking for it relative to
enis being executed. One solution is to turn the relative path into an absolute path. To do that,
where the Python script tb
elo
we need the special __file__
ja ng variable (that’s two underscores on each side of “file”. __file__ is a special
N g s
variable that holds a relative path to the Python script from the present working directory. To see how it works, run
file-processing/Demos/special_file_variable.py, which simply runs print(__file__), from
different directories:
PS …\Webucator\Python> cd file-processing/Exercises
PS …\file-processing\Exercises> python ../Demos/special_file_variable.py
../Demos/special_file_variable.py
Th
is
do
cu
me
We can take the absolute nt path to the folder holding the Python script and combine it with the parts of the relative
be
lon to create an absolute path, like this:
path to the file we want jto open
No agta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
relative_path = "my_files/zen_of_python.txt"
pie om WAR
sa JA
llo GT
we AP
# Get absolute path to Python script ! d .
abs_path = [Link](__file__)
1. import
T os
his
2. do
cu
m
3. relative_pathent= "my_files/zen_of_python.txt"
be
ng__file__) lo
4. ja
print("__file__:",
N s g
5.
6. # Get absolute path to Python script
7. abs_path = [Link](__file__)
8. print("abs_path:", abs_path)
9.
10. # Get absolute path to the directory that the script is in
11. folder = [Link](abs_path)
Th
is
12. do
print("dir:", folder)
cu
13. men
tb
14.
e
lon path on the forward slash
# Split the relative
No jagta gs to
15. p
path_parts =unrelative_path.split("/")
NI
au nilka LK
t
16. h
print("path_parts:", o n t @ ANT
riz path_parts)
ed re ES
17. co diff.c HW
pie o AR
sa m
18. # Join dir with path_parts to llo get an JA
absolute
GT path to the file to open.
we AP
19. d
new_path = [Link](folder, ! *path_parts) .
20. print("new_path:", new_path)
Code Explanation
Th
is
do
This will output something like:
cu
me
nt
be
lon
No agta gs to
j
un p NI
PS …\file-processing\Demos>au nilka python L relpath_to_abspath.py
tho nt@ KAN
__file__: relpath_to_abspath.py r ize T
d c rediff ESH
op . WA
ies com
abs_path: C:\Webucator\Python\file-processing\Demos\relpath_to_abspath.py
R
all JA
dir: C:\Webucator\Python\file-processing\Demos ow GT
ed AP
path_parts: ['my_files', 'zen_of_python.txt']
! .
new_path: C:\Webucator\Python\file-processing\
Demos\my_files\zen_of_python.txt
Th
For reuse purpose, we can create a function that takes a relative path to the file and returns an absolute path to the
is
do
same file: cum
en
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
def file_path(relative_path):
r i z @ ANT
ed re ES
folder = [Link]([Link](__file__))
co diff.c HW
pie o AR
path_parts = relative_path.split('/') sa m JA
llo GT
new_path = [Link](folder, we *path_parts)
AP
d! .
return new_path
Finally, we use that function in file-processing/Demos/[Link] so that we can run the script from
anywhere:
Th
is
do
cu
Demo 81: file-processing/Demos/[Link]
me
nt
be
lon
N ja g gs
1. import os
2. def file_path(relative_path):
3. folder = [Link]([Link](__file__))
4. path_parts = relative_path.split("/")
5. new_path = [Link](folder, *path_parts)
6. return new_path
7. Th
is
8. do
path_to_file = file_path("my_files/zen_of_python.txt")
c um
en
9. tb
with open(path_to_file) as f:
elo
10. jag ngs
poem =N [Link]()
tap
ou to
n
na N
11. uth ilkan ILKA
ori t@ NT
ze
d c rediff ESH
12. for i, line in enumerate([Link](), 1):
o p . c W
13. print(f"{i}. {line}") ies om AR
all JA
ow GT
ed AP
! .
Th
is
d
45 to o90
cu minutes
me
nt
be
lon
No agta gs to
j
un 36pclaims NI parents give girls boys names, but won’t give boys girls names. Journalists
An article in the Atlantic au nilka that L
tho nt@ KAN
need data to make this kind of riz [Link] on data analysts, many of whom are Python programmers like you,
ed SH
to analyze the data. co diff.c
pie om WAR
sa JA
llo GT
we A
In the file-processing/data directory, there d ! are filesPthat
. contain lists of the most popular names in 1880 and
2018:
1. [Link]
2. [Link]
Th
is
do
cu
3. [Link] me
nt
be
lon
4. [Link] No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz r e TE
ed SH
co diff.c
pie om WAR
The data in these files is from [Link]
sa JA
llo GT
we AP
d!
Using the data in these files, try to answer these questions:.
1. What names that were exclusively boys names in 1880 became exclusively girls names in 2018?
2. What names that were exclusively girls names in 1880 became exclusively boys names in 2018?
Th
is
do
cu
me
nt
Does what you found support be the journalist’s claim?
lon
N ja g gs
Spend as much time as you like on this. It is an opportunity to practice your new Python skills.
Solution: file-processing/Solutions/boys_and_girls.py
1. import os
2.
3. def file_path(relative_path):
T his
4. do
"""Returns absolute path from relative path"""
c um
5. folder = [Link]([Link](__file__))
nt
be
long
6. path_partsja = relative_path.split("/")
s
gta
No
u pn to N
new_path n=a [Link](folder,
7.
uth ilkan ILKA *path_parts)
8. return new_patho r ize t @ N T
d c rediff ESH
op . WA
9. ies com R
all JA
10. def file_to_list(path): ow GT
ed AP
11.
!
"""Returns content of file at path as list"""
.
2. Find all the exclusively boys names and all the exclusively girls names in 1880 and in 2018. We did this by
creating a subtract_lists() function that gets all the items from one list that are not in another list.
Th
is
3. Create a dup() do
cu function that takes two lists and returns a new list of all the items that are in both lists. We
me
use this to compare nt exclusively girls names in 2018 with exclusively boys names in 1880. That tells us what
be
names that used toja belostrictly
n boys names are now strictly girls names. We then do the same thing to
No gta gs to
compare exclusively u p
na boys N
n names in 2018 with exclusively girls names in 1880.
uth ilkan ILKA
ori t N
ze @red TES
4. We then write a list_to_file() dc iff. function
HW and use it to save the results in these new files:
op
ies com AR
a l JA
A. [Link] low GT – We found 16:
ed AP
! .
i. Addison
ii. Allison
iii. Ashley
Th
is
do
iv. Aubrey cu
me
nt
v. Bailey belo
N jag ngs
vi. Charley
vii. Dana
viii. Holly
ix. Ivory
[Link] Kelly
is
do
cu
xi. Lindsey me
nt
be
lon
xii. Madison
No ja gta gs to
un p NI
au nilka LK
tho
xiii. Monroe riz
n t @ ANT
ed re ES
co diff.c HW
pie o AR
xiv. Palmer sa m JA
llo GT
we AP
d! .
xv. Shelby
xvi. Sydney
Th
is
do
cu
men
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .
Th
is
do
cu
men
tb
elo
jag ng
N s