Beginning Programming with Python For Dummies
Book image
Explore Book Buy On Amazon
While you can use Python to delete information from files, you may find you no longer need the file at all. The following steps describe how to delete files that you no longer need.
  1. Open a Python File window.

    You see an editor in which you can type the example code.

  2. Type the following code into the window — pressing Enter after each line:

  3. Choose Run→Run Module

    The application displays the File Removed! message. When you look in the directory that originally contained the ChangedFile.csv file, you see that the file is gone.

    The task looks simple in this case, and it is. All you need to do to remove a file is call os.remove() with the appropriate filename and path (Python defaults to the current directory, so you don’t need to specify a path if the file you want to remove is in the default directory). The ease with which you can perform this task is almost scary because it’s too easy.

    Putting safeguards in place is always a good idea. You may want to remove other items, so here are other functions you should know about:

    • os.rmdir(): Removes the specified directory. The directory must be empty or Python will display an exception message.

    • shutil.rmtree(): Removes the specified directory, all subdirectories, and all files. This function is especially dangerous because it removes everything without checking (Python assumes that you know what you’re doing). As a result, you can easily lose data using this function.

About This Article

This article is from the book:

About the book author:

John Paul Mueller is a freelance author and technical editor with more than 107 books and 600 articles to his credit. His subjects range from networking and artificial intelligence to database management and heads-down programming. He also consults and writes certification exams. Visit his website at http://www.johnmuellerbooks.com/.

This article can be found in the category: