Pair programming in this lab if you like. You may choose any partner in your lab, or work on your own if you prefer.
Demonstrate your project solution to your lab instructor. Inform your instructor if you will be making any changes before the deadline at midnight.
Removing certain files you no longer need is one of many things you can automate with a Python program of only a dozen or so lines of code. In this lab you will practice writing such a program. It will give you experience using a couple functions in the os module discussed in class (see the posted class notes) and provide some added experience using a simple loop and conditional test.
Create a new directory for this lab (using the shell mkdir command, and create a file named deleter.py in this directory for your program. This program is an application that takes one argument, which is a text string. It deletes all the files in the current directory with the extension .txt which contain the given string. For each file deleted, it also prints a message of the form Deleting filename, where filename is the name of the file being deleted.
To test your program, create a few text files in the current directory, all ending in .txt. Suppose two of them, named test1.txt and test2.txt contain the string "Delete me!", and at least one other .txt file does not contain this string. Then the command
> python deleter.py 'Delete me!'
should print
Deleting test1.txt Deleting test2.txt
and delete the two indicated files (and not any others!). To be sure you do not delete unintended files, run the program first with the print statement but without the call to os.remove. Then add the remove function call, invoke your application again, and use the dir command to see that the files really were deleted.
Hints: Of course develop the program in stages. Start by just printing out a list of the files in the current directory that have names ending in .txt. Remember that the built-in function open is used to open files, the method close is used to close them, and the string method .count (among others) may be used to see if a string contains a given substring. If you try to delete a file that is open, you will get a permission denied error, so you have to close the file before deleting it. Of course you should also close a file if you open it and decide not to delete it.
Before the end of the lab, submit your deleter.py file using Vincent as lab 13.
There are no more assignments.