
Next, we’ll use the same info.txt document from the previous section to demonstrate how slice notation can be used to clear lines from a text file. By defining the start, end, and step of the slice, we’ll obtain a subset of the original list. The following example shows how slice notation works. Slice notation uses a special syntax to find a subset of a range of values.

Using this Python feature, we can define the start and end indexes of a given subset. With Python slice notation, it’s possible to retrieve a subset of a list, string, or tuple. Clear a Text File Using Python List Slicing Using the truncate() method in this manner will reduce the file size to 0, erasing any content the file contained.
#WHEN YOUTYPE A TEXT AND DELETE IT CODE#
The above Python code will clear a text file of it’s content. This is necessary in order for the truncate method to work.īy passing a value of 0 to the truncate() method, it’s possible to clear the text file completely. Notice that we opened the file in both read and write mode. In the above example, the truncate() method reduced the file to the first 16 characters of text. One of Python’s strengths is readability. Python is a general purpose programming language. We’ll use a demo text file to test Python’s capabilities for truncating files: For example, the program may add white space to the end of the file if the truncate size exceeds the original file size. If no argument is supplied, the file is left unchanged.Īn attempt to truncate a file to longer than its original size may have unexpected results. This method takes an optional argument that sets the new size of the file. The truncate() method reduces a document’s size.
#WHEN YOUTYPE A TEXT AND DELETE IT HOW TO#
How to Clear a File with the truncate() Method Using with to open a file in write mode will also clear its data. The Python with statement simplifies exception handling. The simplest way to delete a file is to use open() and assign it to a new variable in write mode. Also, if the file specified doesn’t exist, Python will create a new one. Opening a file in write mode clears its data.

The open() function takes two arguments, the text file we’d like to open and the mode we’re opening it in. Opening a file in write mode will automatically delete the file’s contents. Clear a Text File Using the open() Function in write Mode
