- Clear File Contents with Python
- Using truncate() to Clear File Contents in Python
- Remove Specific Lines from File in Python
- Other Articles You’ll Also Like:
- About The Programming Expert
- How to Clear a Text File in Python
- Clear a Text File Using the open() Function in write Mode
- How to Clear a File with the truncate() Method
- Clear a Text File Using Python List Slicing
- How to Delete Specific Lines from a Text File
- Clear the First Line of a Text File
- Clear Multiple Lines from a Text File
- How to Clear a Text File Using a String
- Summary
- Related Posts
- Clear a File in Python
- Use the truncate() Function to Clear the Contents of a File in Python
- Use the write Mode to Clear the Contents of a File in Python
- Related Article — Python File
Clear File Contents with Python
To clear the contents of a file in Python, the easiest way is to open the file in write mode and do nothing.
with open("example.txt",'w') as f: pass
Another way you can erase all contents in a file is with the truncate() function.
with open("example.txt",'w') as f: f.truncate(0)
If you want to clear only certain lines from a file, you can use the following method.
with open("example.txt",'r+') as f: lines = f.readlines() f.seek(0) f.truncate(0) f.writelines(lines[5:]) #removes first 5 lines from file
When working with files in Python, the ability to easily be able to modify and change the file content can be useful.
One such situation is if you want to clear a file and delete all of the contents in the file.
To clear the contents of a file in Python, the easiest way is to open the file in write mode and do nothing.
Below shows you how to delete all of the contents from a file in Python.
with open("example.txt",'w') as f: pass
Using truncate() to Clear File Contents in Python
You can also use the truncate() function to clear a file and remove all the content in a file.
Below shows you how to remove everything from a file with truncate() in Python.
with open("example.txt",'w') as f: f.truncate(0)
Remove Specific Lines from File in Python
If you want to remove specific lines from a file, then you can do the following.
with open("example.txt",'r+') as f: lines = f.readlines() f.seek(0) f.truncate(0) f.writelines(lines[5:]) #removes first 5 lines from file
Hopefully this article has been helpful for you to learn how to clear a file in Python.
Other Articles You’ll Also Like:
- 1. Scroll Down Using Selenium in Python
- 2. pandas covariance – Calculate Covariance Matrix Using cov() Function
- 3. Using Python to Split String by Newline
- 4. Set Widths of Columns in Word Document Table with python-docx
- 5. Using Python to Check if Number is Divisible by Another Number
- 6. Squaring in Python – Square a Number Using Python math.pow() Function
- 7. Using Python to Split String by Tab
- 8. Are Dictionaries Mutable in Python? Yes, Dictionaries are Mutable
- 9. Using Python to Print Plus or Minus Sign Symbol
- 10. How to Output XLSX File from Pandas to Remote Server Using Paramiko FTP
About The Programming Expert
The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.
Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.
At the end of the day, we want to be able to just push a button and let the code do it’s magic.
You can read more about us on our about page.
How to Clear a Text File in Python
While programs are often used to create files, there are times when programmers also need to erase file data. Luckily, there are multiple ways to clear text from a file. In this post, we’ll use some simple examples to demonstrate how to clear a text file in Python.
By making use of some of Python’s standard tools, we can open, read, and clear text files. We’ll also learn how to remove specific lines from a text file using slice notation.
Python simplifies the process of file handling, resulting in more succinct programs. As a result of studying this guide, you’ll understand how Python can clear text files and delete lines of data.
Clear a Text File Using the open() Function in write Mode
Opening a file in write mode will automatically delete the file’s contents. 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 clears its data. Also, if the file specified doesn’t exist, Python will create a new one. The simplest way to delete a file is to use open() and assign it to a new variable in write mode.
file_to_delete = open("info.txt",'w') file_to_delete.close()
The Python with statement simplifies exception handling. Using with to open a file in write mode will also clear its data. A pass statement completes the example.
# clear the data in the info file with open("info.txt",'w') as file: pass
How to Clear a File with the truncate() Method
The truncate() method reduces a document’s size. This method takes an optional argument that sets the new size of the file. If no argument is supplied, the file is left unchanged.
An attempt to truncate a file to longer than its original size may have unexpected results. For example, the program may add white space to the end of the file if the truncate size exceeds the original file size.
We’ll use a demo text file to test Python’s capabilities for truncating files:
info.txt
Guido van Rossum created Python in 1991.
Python is a general purpose programming language.
One of Python’s strengths is readability.
with open("info.txt",'r+') as file: file.truncate(16) # read the file’s contents with open("info.txt", 'r') as file: lines = file.readlines() for line in lines: print(line)
In the above example, the truncate() method reduced the file to the first 16 characters of text. Notice that we opened the file in both read and write mode. This is necessary in order for the truncate method to work.
By passing a value of 0 to the truncate() method, it’s possible to clear the text file completely.
with open("example.txt",'r+') as file: file.truncate(0)
The above Python code will clear a text file of it’s content. Using the truncate() method in this manner will reduce the file size to 0, erasing any content the file contained.
Clear a Text File Using Python List Slicing
With Python slice notation, it’s possible to retrieve a subset of a list, string, or tuple. Using this Python feature, we can define the start and end indexes of a given subset.
Slice notation uses a special syntax to find a subset of a range of values. The following example shows how slice notation works. By defining the start, end, and step of the slice, we’ll obtain a subset of the original list.
nums = [1,2,3,4,5,6,7,8,9] sub = nums[1:8:2] print(sub)
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. The readlines() method will return a list of the lines of text in the document.
After the lines are extracted, we can use slice notation to create a new list that we’ll use to overwrite the old file. Only the first line of text will remain. The others will be cleared from the text file.
# read the file's contents read_file = open("info.txt",'r') lines = read_file.readlines() read_file.close() write_file = open("info.txt",'w') # slice the file's content lines = lines[:1] for line in lines: write_file.write(line) print(line) write_file.close()
Guido van Rossum created Python in 1991.
How to Delete Specific Lines from a Text File
Using some common Python functions, we can also clear specific lines of data from text files. It’s especially helpful if we know which lines we want to remove ahead of time. In that case, we can use slice notation to retrieve a subset of the file.
By writing over a file with a subset of its data, we can remove lines of text. The following examples use an excerpt from the poem “Dream Deferred” by the American writer Langston Hughes.
dream.txt
What happens to a dream deferred?
Does it dry up
Like a raisin in the sun?
Clear the First Line of a Text File
In order to clear the first line of text from a file, we’ll need to use a few of Python’s file handling methods. Firstly, we’ll use readlines() to get a list of the file’s text data. With the seek() method, we can manually reposition the file pointer.
Secondly, we can use the truncate() method to resize the file. Thirdly, we’ll write a new list of lines to the file. Using slice notation, it’s possible to omit the first line of the original file.
with open("dream.txt",'r+') as file: # read the lines lines = file.readlines() # move to the top of the file file.seek(0) file.truncate() file.writelines(lines[1:]) with open("dream.txt",'r') as file: lines = file.readlines() for line in lines: print(line)
Does it dry up Like a raisin in the sun?
Clear Multiple Lines from a Text File
It’s also possible to remove more than one line of text from a file. With slice notation, we can create any subset of the data we want. Using this method of overwriting the original file, we can effectively clear the file of any unwanted data.
By changing the start and end indexes of the slice, we’ll get a different subset of the dream.txt file. It’s also possible to combine sliced lists. Using these tools offers plenty of versatility when it comes to creating subsets of lists.
with open("dream.txt",'r+') as file: # read the lines lines = file.readlines() # move to the top of the file file.seek(0) file.truncate() file.writelines(lines[:3]) with open("dream.txt",'r') as file: lines = file.readlines() for line in lines: print(line)
What happens to a dream deferred?
How to Clear a Text File Using a String
What if we want to remove a line from a string that contains a certain word, phrase, or number? We can use a Python if statement to check the string data of each line. If the string we’re looking for is in the line, we can avoid including it in the output file.
employee.txt
Name: Jamie Jameson
Age: 37
Occupation: Copywriter
Starting Date: April 3, 2019
In this example, we need to open the file three times. To begin, we’ll open the file to extract its contents. Next, we’ll write the data to a new file, clearing the lines we don’t want. Lastly, we’ll need to open the file and read it to prove that the file was handled correctly.
data_file = open("employee.txt",'r') lines = data_file.readlines() data_file.close() write_file = open("employee.txt",'w') for line in lines: if "Age" not in line: write_file.write(line) write_file.close() read_file = open("employee.txt",'r') lines = read_file.readlines() read_file.close() for line in lines: print(line)
Name: James Jameson Occupation: Copywriter Starting Date: April 3, 2019
Summary
In this post we’ve taken an in-depth look at how to clear text files in Python. We’ve seen that the Python language offers many options for completing this task. Using some of the methods and functions that come standard with every install of Python, we are able to clear entire files as well remove specific lines from a file.
While tools like slice notation are great for clearing text files, they come in handy in other areas too. In this way, each new feature of Python that you study will improve your overall coding abilities.
Related Posts
If you found this post helpful and would like to learn more about programming with Python, follow these links to more great articles from our team at Python For Beginners. Whether it’s file handling and data management, you’ll learn the skills needed to thrive in today’s rapidly changing, digital world.
Clear a File in Python
- Use the truncate() Function to Clear the Contents of a File in Python
- Use the write Mode to Clear the Contents of a File in Python
In this tutorial, we will introduce how to clear a file in Python.
Use the truncate() Function to Clear the Contents of a File in Python
The truncate() method in the Python file handling allows us to set the size of the current file to a specific number of bytes. We can pass the desired size to the function as arguments. To truncate a file, we need to open it in append or read mode. For example.
with open("sample.txt", 'r+') as f: f.truncate(4)
Notice that the file is opened in read and write mode. The above code resizes the sample file to 4 bytes. To clear all the contents of a file, we simply pass 0 to the function as shown below.
with open("sample.txt", 'r+') as f: f.truncate(0)
This method is handy when we want to read a file and remove its contents afterward. Also, note that if one needs to write to this file after erasing its elements, add f.seek(0) to move to the beginning of the file after the truncate() function.
Use the write Mode to Clear the Contents of a File in Python
In Python, when we open a file in write mode, it automatically clears all the file content. The following code shows how.
with open("sample.txt",'w') as f: pass
When we open the file in write mode, it automatically removes all the contents from the file. The pass keyword here specifies that there is no operation executed.
Another method of achieving the same is shown below:
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.