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 text or binary files, you could 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.
In this recipe, we will learn how to implement this pattern for a text file.
Getting ready
For the purpose of this recipe, we will consider removing empty lines, or lines that start with a semicolon (;
), from a text file. 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...