Removing content from a file
Operations such as copying, renaming, moving, or deleting files are directly provided by the filesystem
library. However, when it comes to removing content from a file, you must perform explicit actions. Regardless of whether you need to do this for a text or binary files, you must implement the following pattern:
- Create a temporary file.
- Copy only the content that you want from the original file to the temporary file.
- Delete the original file.
- Rename/move the temporary file to the name/location of the original file.
Getting ready
In this recipe, we will see how to implement the pattern mentioned earlier for a text file. To do this, we will consider removing empty lines or lines that start with a semicolon (;
). For this example, we will have an initial file called sample.dat
that contains the names of Shakespeare's plays, but also empty lines and lines that start with a semicolon. The following is a partial listing of this file (from the beginning):
;Shakespeare's plays...