Clear a File in Python
In this tutorial, we will introduce how to clear a file in Python.
Please enable JavaScript
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.
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.
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.
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.
Очистка файла
Иногда возникают ситуации, когда надо произвести запись в файл, в котором уже находятся данные. Или просто удалить все содержимое. Рассмотрим, как выполнить очистку этого файла средствами Python 3.
Способы
Очистить файл в Python 3 можно следующими способами:
- При открытии использовать режим, в котором указатель находится в начале документа.
- Вручную переместить указатель в начальную позицию.
- Средствами операционной системы обнулить содержимое файла.
Рассмотрим эти варианты подробно.
При открытии
Когда файл открывается на запись, то указатель текущего положения в документе может быть расположен в начале или в конце документа. Если указатель в конце, то данные будут дописываться. Нас же интересует вариант, когда указатель расположен в начале.
Здесь w – указывает режим открытия файла на запись в текстовом режиме с размещением указателя в начале. После выполнения этого кода, если существовал указанный файл, то содержимое его очистится. Если его не было, то создастся новый пустой.
Перед закрытием, можно было добавить информацию. Она будет записана с начала файла, а не дописана в конец.
Если надо записывать данные в бинарный файл, то следует использовать режим “wb”.
Если же наоборот, нам нужно добавить информацию в конец файла. При этом старые данные чтобы остались. В этом случае к режиму следует добавить символ +. Режим открытия текстового документа будет “w+”, а бинарного “wb+”.
Дополнительную информацию по режимам открытия можно получить в отдельной статье на нашем сайте.
Перемещение указателя
Если мы открыли файл на запись и не знаем, в каком месте находится указатель. Возможно, мы уже записали какие то данные. Мы можем просто переместить указатель в начало и закрыть его. В этом случае документ будет пустым.
В этом примере открытие сделали специально в режиме дозаписи. После закрытия, даже если в файле были данные, они удалятся.
Вот еще пример, здесь мы записываем данные, потом переносим указатель в начало. После этого еще раз производим запись. В итоге, в конце работы, в файле будет только последняя сделанная запись. Те данные, которые были внесены вначале, благополучно удалятся.
Средствами ОС
Для очистки с помощью средств операционной системы воспользуемся стандартной библиотекой os. Вначале её надо подключить с помощью инструкции import os.
На linux должно пройти следующим образом.
Можно воспользоваться командами cp или cat. Вот пример решения с помощью cat.
Delete Lines From a File in Python
This article lets you know how to delete specific lines from a file in Python. For example, you want to delete lines #5 and #12.
After reading this article, you’ll learn:
- How to remove specific lines from a file by line numbers
- How to delete lines that match or contain the given text/string
- How to delete the first and last line from a text file.
Table of contents
Delete Lines from a File by Line Numbers
Please follow the below steps to delete specific lines from a text file by line number: –
-
in a read mode . Read all contents from a file into a list using a readlines() method. here each element of a list is a line from the file
- Close a file
- Again, open the same file in write mode.
- Iterate all lines from a list using a for loop and enumerate() function. The enumerate() function adds a counter to an iterable (such as list, string) and returns it in enumerate object. We used the enumerate object with a for loop to access the line number
- Use the if condition in each iteration of a loop to check the line number. If it matches the line number to delete, then don’t write that line into the file.
- Close a file
Example:
The following code shows how to delete lines from a text file by line number in Python. See the attached file used in the example and an image to show the file’s content for reference.

text file
In this example, we are deleting lines 5 and 8.
Our code deleted two lines. Here is a current data of a file
Note:
The enumerate() function adds a counter to an iterable (such as list, string) and returns it in enumerate object. We used the enumerate object with a for loop to access the line number. The enumerate() doesn’t load the entire list in memory, so this is an efficient solution.
Note: Don’t use del keywords to delete lines from a list and write the same list to file. Because when you delete a line from the list, the item’s index gets changed. So you will no longer be able to delete the correct line.
Using seek() method
The same can be accomplished using the seek() method by changing the pointer position so we don’t need to open a file twice.
- Open file in the read and write mode ( r+ )
- Read all lines from a file into the list
- Move the file pointer to the start of a file using seek() method
- Truncate the file using the truncate() method
- Iterate list using loop and enumerate() function
- In each iteration write the current line to file. Skip those line numbers which you want to remove
Example:
Delete First and Last Line of a File
To selectively delete certain content from the file, we need to copy the file’s contents except for those lines we want to remove and write the remaining lines again to the same file.
Use the below steps to delete the first line from a file.
- Open file in a read and write mode ( r+ )
- Read all lines from a file
- Move file pointer at the start of a file using the seek() method
- Truncate the file
- Write all lines from a file except the first line.
Output
Before deleting the first line
After deleting the first line
To delete the first N lines use list slicing.
If you are reading a file and don’t want to read the first line use the below approach instead of deleting a line from a file.
Use the below example to steps to delete the last line from a file
To delete last N lines use list slicing.
Deleting Lines Matching a text (string)
Assume files contain hundreds of line and you wanted to remove lines which match the given string/text. Let’s see how to remove lines that match the given text (exact match).
Steps:
- Read file into a list
- Open the same file in write mode
- Iterate a list and write each line into a file except those lines that match the given string.
Example 1: Delete lines that match the given text (exact match)
Also, you can achieve it using the single loop so it will be much faster.
Remove Lines that Contains a Specific Word
We may have to delete lines from a file that contains a particular keyword or tag in some cases. Let’s see the example to remove lines from file that contain a specific string anywhere in the line.
Example:
Remove Lines Starting with Specific Word/String
Learn how to remove lines from a file starting with a specific word. In the following example, we will delete lines that begin with the word ‘time‘.
Example:
Delete Specific Text from a Text File
It can also be the case that you wanted to delete a specific string from a file but not the line which contains it. Let’s see the example of the same
Delete all Lines From a File
To delete all the lines in a file and empty the file, we can use the truncate() method on the file object. The truncate() method removes all lines from a file and sets the file pointer to the beginning of the file.
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
Удалить содержимое файла (Truncate File) в Python
В этом посте мы обсудим, как удалить содержимое файла в Python. По порядку слов, обрезать файл до 0 байт.
1. Использование ‘w’ Режим
Самое простое решение — открыть файл в w режим, который открывает его для записи. Файл создается, если он не существует; в противном случае он усекается. Вот как будет выглядеть код:
Приведенный выше код явно закрывает обработчик файла с close() функция. Этого можно избежать с помощью with оператор, который автоматически закрывает обработчик файла по завершении работы с ним. Вот пример использования with утверждение:
2. Использование truncate() функция
Кроме того, вы можете открыть файл для обновления (чтения и записи), не усекая его. Это можно сделать с помощью r+ режим, который не удаляет содержимое и не создает новый файл, если он не существует. Затем, чтобы обрезать файл до 0 байт, используйте truncate() функция.
Это все об удалении содержимого файла в Python.
Оценить этот пост
Средний рейтинг 5 /5. Подсчет голосов: 20
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования