Introduction to Python

davidbpython.com




In-Class Exercises, 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.

 
Ex. 10.2 List a directory.

Loop through the testdir/ directory list, printing each item. Use os.listdir(). (Note: don't forget to import os.)

import os

this_dir = 'testdir'
Expected Output:
file1.txt
file2.txt
file3.txt
testdir2
testdir3

(your file output order may be different)

 
Ex. 10.3 Build a filepath.

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

import os

dirname = 'python_data/'

filename = 'pyku.txt'
Expected Output:
python_data/pyku.txt

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

import os

fname = 'pyku.txt'
Expected Output:
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().

import os

dirname = 'shakespeare'
Expected Output:
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().

import os

fname = 'pyku.txt'
Expected Output:
80
 

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.

dirname = 'testdir'
Expected Output:
testdir/file2.txt
testdir/file3.txt
testdir/file1.txt
testdir/testdir3
testdir/testdir2

Note the above 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'

items = os.listdir(dirname)

for name in items:
    fpath = os.path.join(dirname, name)
    print(fpath)
Expected Output:
testdir/file2.txt 752
testdir/file3.txt 200
testdir/testdir3 160
testdir/testdir2 128
 
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'

entries = os.listdir(dirnames)

for name in entries:
    fpath = os.path.join(dirname, name)
    print(fpath)
Expected Output:
testdir/file2.txt:  file
testdir/file3.txt:  file
testdir/testdir3:  dir
testdir/testdir2:  dir

In the above example, I am using an f'' strings to print the colon and file or dir after each entry.

 
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.

filename = input('please enter a filename: ')
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.

# your function def here



# 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')
      # NotADirectoryError:  directory "wrong" could not be opened
 

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

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

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

 
[pr]