Introduction to Python

davidbpython.com




In-Class Exercise Solutions, Session 10



PLEASE REFER to pythonreference.com for syntax to follow in coding these Exercises

 

FILE INSPECTIONS

 
Ex. 10.1 Show the present/current working directory.

This is the one from which you are running your Python program. In most cases (but not always) it is the same as the location of the file you are running. Use os.getcwd(). Remember to import os.

import os

cwd = os.getcwd()        # str (your current directory)

print(cwd)
 
Ex. 10.2 List a directory.

Loop through the testdir/ directory list, printing each item. Use os.listdir().

import os

this_dir = 'testdir'     # str, 'testdir'

items = os.listdir(this_dir)

for item in items:    # str, 'file1.txt' (sample)
    print(item)
 
Ex. 10.3 Build a filepath.

Given the below directory name and filename, build a complete filepath. Use os.path.join()

dirname = 'python_data/'       # str, 'python_data/'

filename = 'pyku.txt'          # str, 'pyku.txt'

filepath = os.path.join(dirname, filename)  # str, 'python_data/pyku.txt'

print(filepath)

Note that on Windows computers, os.path.join() will insert a backslash instead of a forward slash. This completed path is still valid.

 
Ex. 10.4 Check to see if an entry is a file.

Given the below filename, confirm that the entry is a file by printing is a file!. Use os.path.isfile().

fname = 'pyku.txt'            # str, 'pyku.txt'

if os.path.isfile(fname):        # bool, True
    print('is a file!')
 
Ex. 10.5 Check to see if an entry is a directory.

Given the below directory name, confirm the entry is a directory by printing is a directory!. Use os.path.isdir().

dirname = 'shakespeare'        # str, 'shakespeare'

if os.path.isdir(dirname):        # bool, True
    print('is a directory!')
 
Ex. 10.6 Get the size of a file.

Given the below filepath, check the size of the file. Use os.path.getsize().

fname = 'pyku.txt'                    # str, 'pyku.txt'

bytesize = os.path.getsize(fname)        # int, 80
print(bytesize)
 

LAB 2

 
Ex. 10.7 List a directory and show full path to each file.

Starting with the below directory, list the directory's contents, joining each entry to the directory name so it becomes a full path to the directory.

import os

dirname = 'testdir'                     # str, 'testdir'

items = os.listdir(dirname)

for entry in items:                        # str, 'file1.txt'
    fpath = os.path.join(dirname, entry)   # str, 'testdir/file1.txt'
    print(fpath)

Note that your results may be in a different order on your system. Also, you may see additional entries .DS_Store, .Trashes or other "hidden" files starting with a period.

 
Ex. 10.8 List a directory and show file sizes.

Extend the previous solution by printing the file size of each file or directory. Use a comma between varaible names to print two values on the same line, e.g. print(this, that).

import os

dirname = 'testdir'                    # str, 'testdir'

entries = os.listdir(dirname)

for name in entries:                      # str, 'file1.txt' (sample first file)
    fpath = os.path.join(dirname, name)   # str, 'testdir/file1.tsxt'
    fsize = os.path.getsize(fpath)        # int, 33
    print(fpath, fsize)
 
Ex. 10.9 List a directory and identify file or directory.

Modify the previous solution so that the program identifies each listing as either a file or directory.

import os

dirname = 'testdir'                   # str, 'testdir'

items = os.listdir(dirname)

for name in items:                       # str, 'file1.txt' (sample first file)
    fpath = os.path.join(dirname, name)  # str, 'testdir/file1.txt'
    if os.path.isdir(fpath):             # bool, False
        print(f'{fpath}:  dir')
    elif is.path.isfile(fpath):          # bool, True
        print(f'{fpath}:  fpath')
 
Ex. 10.10 See if a file exists as a file; if not, show present working directory.

Take input for a filepath; check to see if the file exists. If not, show the present working directory.

import os
filename = input('please enter a filename: ') # str, 'thisfile.txt'

# could also use os.path.isfile()
if os.path.exists(filename):                  # bool, True
    cwd = os.getcwd()                         # str, '/Users/yourname' (sample dir)
    print(f'"filename" does not exist.  Present working directory is {cwd}')
If the file can't be opened, we should see a message like this one:
Error:  "thisfile.txt" does not exist.  Present working directory is
/Users/david/Downloads/python_data/08
 
Ex. 10.11 A function to generate a file listing.

Write a function get_listing() that takes a directory name and returns the list of entries in that directory. If the directory name is not a valid directory, have the function raise a NotADirectoryError exception.

import os

def get_listing(dirname):            # dirname: str, '.'
    if not os.path.isdir(dirname):   # bool, False
        raise NotADirectoryError(f'directory "{dirname}" could not be opened')
    items = os.listdir(dirname)
    return items

# this should succeed
listing = get_listing('.')      # list, (files and dirs in this dir)
print(listing)
print()


# this should raise NotADirectoryError exception
listing = get_listing('wrong')  # raises NotADirectoryError
 

WRITING TO FILES

 
Ex. 10.12 Write to a file. Open a file for writing (using a new filename such as newfile.txt and the additional argument 'w') and write some text to it (using the file .write() method. After running the program/cell, open the file and look at it to see it has been written to (make sure to call .close() on the file or you may not see the written text.)
wfh = open('newfile.txt', 'w')        # 'file' object

wfh.write('here is some text')        # int, 17

wfh.close()
 
Ex. 10.13 Write lines to a file, including newlines. Open a file for writing (using a new filename) and write 3 lines to it (they can be as simple as 'line1', 'line2' and 'line3'. Add the newline character to each line. After running the program/cell, open the file and look at it to see it has been written to (make sure to call .close() on the file or you may not see the written text.)
wfh = open('newfile.txt', 'w')           # 'file' object

wfh.write('here is some text\n')         # int, 18
wfh.write('here is some more text\n')    # int, 23
wfh.write('here is some more...\n')      # int, 21

wfh.close()
 
Ex. 10.14 Append to an existing file. Open the file you created previously for appending (using the 'a' argument instead of 'w') and write one or more additional lines to it. Again, add the newline character to each line. After running the program/cell, open the file and look at it to see it has been written to (make sure to call .close() on the file or you may not see the written text.)
afh = open('newfile.txt', 'a')           # 'file' object

afh.write('THIS IS ONE MORE LINE...\n')  # int, 25

afh.close()
 
[pr]