8. Working with files and folders

8. Working with files and folders#

Exercise 8.1.#

The ‘Data’ folder contains a file named ‘sonnet116.txt’. It is the full text of a Shakespeare sonnet.

Print the poem on your screen, and make sure that you also add line numbers, as follows:

1. [line1]
2. [line2]
sonnet = open( 'sonnet116.txt' , encoding = 'utf-8' )

line_nr = 0

for line in sonnet:
    line_nr += 1
    print(f'{line_nr}. {line}')

Exercise 8.2.#

The dictionary below is an excerpt from a longer dictionary which connects country codes to the full names of these countries. Working with this dictionary, create a Comma Separated Value (CSV) file with two columns, named ‘code’ and ‘country_name’. The first column should contain the keys of the dictionary, and the second column should contain the values associated with these keys. This new CSV file should be saved under the name ‘country_codes.csv’.

country_codes = {'AFG': 'Afghanistan',
 'ALB': 'Albania',
 'DZA': 'Algeria',
 'ASM': 'American Samoa',
 'AND': 'Andorra',
 'AGO': 'Angola',
 'AIA': 'Anguilla',
 'ATA': 'Antarctica',
 'ATG': 'Antigua and Barbuda',
 'ARG': 'Argentina',
 'ARM': 'Armenia',
 'ABW': 'Aruba',
 'AUS': 'Australia',
 'AUT': 'Austria',
 'AZE': 'Azerbaijan' }


out = open( 'country_codes.csv' , 'w' , encoding = 'utf-8' )
out.write('code,country_name\n')
for code in country_codes:
    out.write(f'{code},{country_codes[code]}\n')
out.close()

Exercise 8.3.#

Find a directory on your own computer which contains both files and subfolders. Define the path to this folder, as a variable named path.

Next, write some code that can list only the subdirectories in this directories, and which ignores the individual files, using the functions listdir() and isfile.

Finally, also try to list all the files in one of these subdirectories.

import os
from os.path import join, isfile, isdir
from os import listdir

path = join( '..' )

for item in listdir(path):
    if not isfile(join( path, item)):
        print(item)


print('\nFiles in "Data":\n')
        
path = join( '..' , 'Data')

for item in listdir(path):
    if isfile(join( path, item)):
        print(item)