0% found this document useful (0 votes)
5 views27 pages

55284A - Introduction To Python - Chapter10

This lesson covers file processing in Python, including reading, writing, and managing files and directories. It explains how to open files using the built-in open() function with various modes, read file contents, and the importance of closing files properly. Additionally, it provides an exercise for creating a word search tool that locates specified words within a text file.

Uploaded by

ssuresh19747745
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views27 pages

55284A - Introduction To Python - Chapter10

This lesson covers file processing in Python, including reading, writing, and managing files and directories. It explains how to open files using the built-in open() function with various modes, read file contents, and the importance of closing files properly. Additionally, it provides an exercise for creating a word search tool that locates specified words within a text file.

Uploaded by

ssuresh19747745
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

LESSON 10: File Processing

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.

5. List directory contents.

6. Rename files and directories.


Th
is
do
cu
me
nt
be
Opening Files lon
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz r e to TE
The built-in open() function will ed attempt open
SH a file at a given path and return a corresponding file object, which
co diff.c WA
can be read and, if opened with the right p i o
es permissions,
m R written to. This is the most basic syntax for opening a file:
all JA
ow GT
ed AP
! .

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! .

open('[Link]') # Open for reading


open('[Link]', 'w') # Open for writing
open('[Link]', 'r+') # Open for reading and writing
Th
open('[Link]', 'r+b') # Open in binary mode for reading and writing
is
do
cu
men
tb
elo
n
No agta gs to
j
Methods of File u na Objects
p n N
uth ilkan ILKA
ori t N
ze @red TES
Reading Files dc iff HW
op .
ies com AR
all JA
Once you have a file object, you can read w o the GT using any of the following methods:
ed file contents
AP
! .

[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.

Demo 73: file-processing/Demos/[Link]

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! .

Run this file by opening the terminal at file-processing/Demos/ and running:

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
! .

Exercise 29: Finding Text in a File

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: ! .

Demo 74: file-processing/Demos/simple_write.py

1. with open('my_files/[Link]', 'w') as f:


Th
i
sd
2. [Link]('Powerful
o you have become.')
cu
men
tb
elo
jag ng
Code Explanation N s
1. Before running this file, look in the file-processing/Demos/my_files folder. It should not contain a
[Link] file. If it does, delete it.

2. Now, run the following from file-processing/Demos at the terminal:

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 open('my_files/[Link]', 'a+') as f:


Th
is
2. do
[Link]('Powerful you have become.')
cu
3. en
print([Link]())
m
tb
elo
n
No jagta gs to
un p NI
au nilka L
Code Explanation tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
By changing the mode to “a+”, the file sisa opened for Jappending
AG and reading. However, when a file is opened for
llo
w TA
appending, the cursor is placed at the end ofedthe file, and Pwhen you read from the file, it begins where the cursor is,
! .
which is why print([Link]()) doesn’t output anything.

Challenge Solution: file-processing/Solutions/simple_write_challenge.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.

Exercise 31: List Creator


Th
is
do
cu
en m
tb
30 to 45 minutes elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
r
In this exercise, you will createead modulee that ES allows you to maintain a list of items in a file.
co diff.c HW
pie o AR
sa m JA
llo GT
1. Open file-processing/Exercises/list_creator.py we AP in your editor.
d! .
2. The main() and show_instructions() functions are already written. Your job is to write the following
functions, which are documented in 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()

3. Now, run the file from file-processing/Exercises at the terminal:

PS …\file-processing\Exercises> python list_creator.py


Th
is
do
cu
m en
tb
elo
N jag ngs
This is the starting code:
ou ta to
na pnilk NIL
uth an K
ori t@ ANT
z e re ES
Exercise Code: file-processing/Exercises/list_creator.py
d
dc
op [Link] HWA
ies m R
all JA
ow GT
ed AP
1. def add_item(item): ! .
2. """Appends item (after stripping leading and trailing
3. whitespace) to [Link] followed by newline character
4.
5. Keyword arguments:
6. Th
item
is -- the item to append"""
o d
7. pass cum
en
tb
8. elo
ng j
9. No agta st
def remove_item(item):o
pn un
ilk NILK
"""Removes utfirst a
10. ho aninstance A of item from [Link]
riz t@re NTE
11. If item is not efound
dc S
din [Link], alerts user.
op [Link] HWA
12. ies m R
all JA
ow GT
13. Keyword arguments: ed AP
! .
14. item -- the item to remove"""
15. pass
16.
17. def delete_list():
18. Th
"""Deletes the entire contents of the list by opening
is
19. oc
[Link]
d
u for writing."""
me
20. pass nt
be
lon
21. No jagta gs to
un p NI
22. au nilka
def print_list(): L
tho nt@ KAN
r i z r e TE
23. """Prints list""" ed SH
co diff.c
24. pass pie om WAR
sa JA
llo GT
25. we AP
d! .
26. def show_instructions():
27. """Prints instructions"""
28. print("""OPTIONS:
29. P
30. Th -- Print List
is
31. +abcdo
cu
m
en 'abc' to list
32. -- Addt be
lo
33. -abc
N jag ngs
34. -- Remove 'abc' from list
35. --all
36. -- Delete entire list
37. Q
38. -- Quit\n""")
39.
40. def main():
Th
is
41. do
show_instructions()
cu
42. men
tb
43.
e
while True: lon
N jag gs
44. choice oNt t
o u =apinput('>> ')
n nil
au I LK
tho kant
45. riz @ ANT
ed re ES
co di==f HW
46. if [Link]() pie [Link]'q': AR
sa m JA
47. print('Goodbye!') llo GT
we AP
48. break d! .
49.
50. if [Link]() == 'p':
51. print_list()
52. elif [Link]() == '--all':
Th
53. is delete_list()
do
cu
54. elifmechoice and choice[0] == '+':
nt
55. be
add_item(choice[1:])
lo
jag ngs
No choice
56. elif tap and to choice[0] == '-':
un NI
au nilka L
57. tho nt@ KAN
remove_item(choice[1:])
riz re TE
ed SH
58. else: co diff.c
pie om WAR
59. print("I didn't s a understand.")
JA
llo GT
we AP
60. show_instructions() d! .
61.
62. if __name__ == '__main__':
63. main()

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():
! .

30. """After confirming user really wants to delete list,


31. deletes the entire contents of the list by opening
32. [Link] for writing."""
33. confirm = input('Are you sure you want to delete the list? y/n ')
Th
34. [Link]()
do == 'y':
cu
35. me open('[Link]', 'w') as f:
with n tb
36. lon e
print('The list has been deleted.')
N jag gs
37. else:
38. print('OK. Whew! That was a close one.')
39.
40. def print_list():
41. """Prints list"""
42. with open('[Link]', 'r') as f:
43. for i, item in enumerate(f, 1):
Th
is
44. do print(i, '. ' + item, sep='', end='')
cu
-------Lines e45 m
n through 83 Omitted-------
tb
elo
n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz TE
The os Module ed re
co diff.c
SH
pie om WAR
sa JA
The os module is a built-in Python module llo for interacting
GT with the operating system. In this section, we cover some
we AP
of its most useful methods. d ! .

[Link]() and [Link](path)

[Link]() returns the current working directory as a string.

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.

Demo 75: file-processing/Demos/directory_list.py

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:

PS …\file-processing\Demos> python directory_list.py


T
a b [Link] his
d oc
d e [Link] um
en
tb
[Link] elo
N jag ngs
g h [Link] ou ta to
na pnilk NIL
[Link] uth an KA
ori t N
ze @red TES
dc
op [Link] HWA
zen_of_python.txt
ies m R
all JA
ow GT
ed AP
! .

[Link](dirname) and [Link](path)

[Link](dirname) creates a directory named dirname. It errors if the directory already


exists. Th
is
do
cu
m
[Link](path) eis
nt like mkdir(), but it creates all the necessary directories along the
be
lon
No agta gs to
j
path.
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
Demo 76: file-processing/Demos/make_dirs.pysa JA
llo GT
we AP
d! .
1. import os
2.
3. [Link]("my_files/a")
4. [Link]("my_files/a/b/c")
5. Th
is
do
cu
6. m
with open('my_files/a/[Link]',
en
'w') as f:
7. be text')
[Link]('Dummy
t
lo n
8. No jagta gs to
with open('my_files/a/b/[Link]', 'w') as f:
un pn
a u ilka NILK
9. [Link]('Dummy tho text')n A
riz t@re NTE
ed d SH
co if
pie [Link] WAR
sa JA
Code Explanation llo GT
we AP
d! .

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.

1. Open the Python terminal at file-processing/Demos.


Th
is
2. Run import do os.
cu
me
nt
3. be
Run [Link]('my_files/a/b/c') to remove directory c.
lon
No agta gs to
j
na pnto
Look in your file usystem NIthat the directory was removed.
4. uth ilkasee LK
ori n t@ ANT
ze
Run [Link]('my_files/a/b') d c rediff ESH
5. op . WA to try to remove both the a and b directories. You will get an
ies com R
error because directory b is not empty. all JA
ow GT
ed AP
! .

[Link](path) and [Link](path)

[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]']

4. Run [Link]('my_files/a/b/[Link]') to remove the file in directory b, and then run


Th
[Link]('my_files/a/b')
is again to show that directory b is now empty:
do
cu
me
nt
be
lon
N ja g gs
>>> [Link]('my_files/a/b/[Link]')
>>> [Link]('my_files/a/b')
[]

5. Now, remove the file from directory a:

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.

Demo 77: file-processing/Demos/[Link]


Th
is
do
cu
1. import os men
tb
2. elo
n
No agta gs to
j
un pn
ilka NILK
3. foo = 'my_files/[Link]'
au
4. t h
bar = 'my_new_files/[Link]'ori nt@ ANT
ze
d c rediff ESH
5. op . WA
ies com R
6. def foo2bar(): a llo JA
we GT
d! AP
7. [Link](foo, bar) .
8. print('Renamed', foo, 'to', bar)
9.
10. def bar2foo():
11. [Link](bar, foo)
12.
This
print('Renamed', bar, 'to', foo)
do
cu
13. m en
tb
14. foo2bar() elo
jag ng
N s
Code Explanation

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(): ! .

4. for dirpath, dirnames, filenames in [Link]('my_files'):


5. for fname in filenames:
6. if ' ' in fname:
7. oldname = dirpath + '/' + fname
Th
8. is newname = dirpath + '/' + [Link](' ', '-')
do
cu
9. men print("Replacing", oldname, "with", newname)
tb
10. [Link](oldname,
lon newname)
No jagta gs to
11. un p NI
au nilka LK
12. t h
def dashes2spaces(): ori n t@ ANT
ze
d c redifffilenames
ES
13. for dirpath, dirnames, op .co HWA in [Link]('my_files'):
ies m R
14. for fname in filenames: all JA
ow GT
ed AP
15. if '-' in fname: ! .
16. oldname = dirpath + '/' + fname
17. newname = dirpath + '/' + [Link]('-', ' ')
18. print("Replacing", oldname, "with", newname)
19. [Link](oldname, newname)
Th
20. is
do
cu
21. m
spaces2dashes()
en
tb
elo
n
No agta gs to
j
un pn NI
Code Explanation au il LK
tho kant
riz @ ANT
ed r e ES
co diff.c H
1. Before running this file, look inpithe om WAR
es file-processing/Demos/my_files folder. It should contain some
all JA
files with spaces in their names (e.g., GT That’s ugly!
owa b [Link]).
ed AP
! .
2. Now, run file-processing/Demos/[Link].

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](path) returns True if path exists.

>>> [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]')
.

>>> last_modified = [Link]('my_files/[Link]')


>>> date_created = [Link]('my_files/[Link]')
>>> last_accessed, last_modified, date_created
(1582050514.8227544, 1581523336.46663, 1580745606.86663)
Th
is
do
>>> from datetime import datetime
cu
me
>>> [Link](last_accessed).strftime('%c')
n tb
e
lon
'Tue Feb 18 13:28:34 2020'
No agta gs to
j
un p NI
>>> [Link](last_modified).strftime('%c')
au nilka LK
t h
'Wed Feb 12 11:02:16 2020' ori n t@ ANT
ze
d c rediff ESH
op .
>>> [Link](date_created).strftime('%c') WA
ies com R
'Mon Feb 3 11:00:06 2020' a llo JA
we GT
d! AP
.

[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](path) returns True if path is an absolute 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]:

Demo 79: file-processing/Demos/[Link]


Th
is
do
cu
me
1. nt
with open('my_files/zen_of_python.txt') as f:
be
lon
2.
No jagta gs to
poem = [Link]()
un p NI
3. au nilka L
tho nt@ KAN
4. # The file is now iclosed, r ze but T we saved its content in the poem variable
d c rediff ESH
op . WA
5. ies com
for i, line in enumerate([Link](), R 1):
all JA
6. print(f"{i}. {line}") ow GT
ed AP
! .

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 …\file-processing\Demos> python special_file_variable.py


special_file_variable.py
Th
is
do
cu
m
PS …\file-processing\Demos> cd ..
en
be
PS …\Python\file-processing>
t
python Demos/special_file_variable.py
lo ng
No ja
gta st
Demos/special_file_variable.py
o
un p NI
au nilka L
tho nt@ KAN
riz red TES
ed
PS …\Python\file-processing> co cd if .. H
pie [Link] WAR
PS …\Webucator\Python> python sfile-processing/Demos/special_file_variable.py
all JA
ow GT
ed
file-processing/Demos/special_file_variable.py AP
! .

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__)

# Get absolute path to the directory that the script is in


folder = [Link](abs_path)
Th
is
do
cu
# Split the relative path on the forward slash
m en
tb
el
path_parts = relative_path.split('/')
on
No jagta gs to
un p N
au nilka toILKget an absolute path to the file to open.
# Join dir with path_parts tho nt@ AN
riz re TE
ed SH
new_path = [Link](folder, co diff*path_parts)
pie . c om WAR
sa JA
llo GT
we AP
d! .
The following script includes print() calls showing the values of the different variables:

Demo 80: file-processing/Demos/relpath_to_abspath.py

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
! .

Exercise 32: Comparing Lists

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"""
.

12. with open(file_path(path)) as f:


13. lines = [Link]().splitlines()
14. return lines
15.
Th
is
16. do
def subtract_lists(list1, list2):
cu
17. me a list of all items in list1, but not in list2"""
"""Returns
n tb
18.
e
return [x forlonx in list1 if x not in list2]
ja
No g st
gta
19. u oNpn
na
uth kan ILKA
i l
ori N
t sort=True):
ze @red TES
20. def dups(list1, list2,
dc iff HWitems in both lists"""
21. op
"""Returns a list containing .
ies com AR
22. dup_list = [] all JA
ow GT
ed AP
23. for item in list1: ! .
24. if item in list2:
25. dup_list.append(item)
26.
27. if sort:
Th
28. is dup_list.sort()
do
cu
29. me
nt
30. return dup_list be
lon
31. No jagta gs to
un p NI
au nilka LK
32. tho
def list_to_file(path, AN
nt@the_list):
riz re TE
e
33. """Creates/Overwrites dc d ff.c Sat
op ifile HW path with content from the_list"""
ies om AR
34. content = "\n".join(the_list) all JA
ow GT
35. ed AP
! .
36. with open(file_path(path), "w") as f:
37. [Link](content)
38.
39.
40. Th
def main():
i sd
oc
41. um
boys_2018_path = "../data/[Link]"
en
42. tb
girls_2018_path = "../data/[Link]"
e lo
43. N jag ng=s "../data/[Link]"
boys_1880_path
44. girls_1880_path = "../data/[Link]"
45.
46. boys_2018 = file_to_list(boys_2018_path)
47. girls_2018 = file_to_list(girls_2018_path)
48. boys_1880 = file_to_list(boys_1880_path)
49. girls_1880 = file_to_list(girls_1880_path)
50.
Th
is
51. do
boys_only_2018 = subtract_lists(boys_2018, girls_2018)
cu
52. me
girls_only_2018 = subtract_lists(girls_2018, boys_2018)
n tb
53. boys_only_1880
e
lon = subtract_lists(boys_1880, girls_1880)
No jagta gs to
54. un
girls_only_1880 p = subtract_lists(girls_1880,
NI boys_1880)
au nilka L
55. tho nt@ KAN
riz re TE
ed SH
co diff.c = dups(girls_only_2018,
56. boys_names_2_girls_names pie om WAR boys_only_1880)
sa J AG
57. girls_names_2_boys_names llo = dups(boys_only_2018, girls_only_1880)
we TA
58. d! P.
59. list_to_file("../data/[Link]",
60. boys_names_2_girls_names)
61. list_to_file("../data/[Link]",
62. girls_names_2_boys_names)
Th
63. is
do
cu
64. main() m en
tb
elo
n
No agta gs to
j
un pn NI
Code Explanation au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
There are different ways of going about pie this.o AR through the following process:
s a m We went JA
llo GT
we AP
d! .
1. Create a file_to_list() function that takes a file path, reads it, and returns a list. We use this function to
create four lists from the four files.

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

B. [Link] – We didn’t find any.

Th results appear to support the journalist’s claim.


These
is
do
cu
me
nt
be
lon
j g
Conclusion No u agtap s to N
na n
uth ilkan ILKA
In this lesson, you have learned o r ize tot@work N T files and directories on the operating system.
with
d c rediff ESH
op . WA
ies com R
all JA
ow GT
ed AP
! .
36. [Link]

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

You might also like