Как очистить файл в python

Sorry, you have been blocked

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.

Cloudflare Ray ID: 752aae883bd99b1c • Your IP: Click to reveal 217.138.221.212 • Performance & security by Cloudflare

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.

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.

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.

Output

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.

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.

Output

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.

Output

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.

Output

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.

Output

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.

Output

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.

How to erase the file contents of text file in Python?

I have text file which I want to erase in Python. How do I do that?

12 Answers 12

Or alternatively, if you have already an opened file:

Opening a file in «write» mode clears it, you don’t specifically have to write to it:

(you should close it as the timing of when the file gets closed automatically may be implementation specific)

Not a complete answer more of an extension to ondra’s answer

When using truncate() ( my preferred method ) make sure your cursor is at the required position. When a new file is opened for reading — open(‘FILE_NAME’,’r’) it’s cursor is at 0 by default. But if you have parsed the file within your code, make sure to point at the beginning of the file again i.e truncate(0) By default truncate() truncates the contents of a file starting from the current cusror position.

As @jamylak suggested, a good alternative that includes the benefits of context managers is:

CasualCoder3

When using with open(«myfile.txt», «r+») as my_file: , I get strange zeros in myfile.txt , especially since I am reading the file first. For it to work, I had to first change the pointer of my_file to the beginning of the file with my_file.seek(0) . Then I could do my_file.truncate() to clear the file.

Writing and Reading file content

It Worked for me

Mohd Tauovir Khan

If security is important to you then opening the file for writing and closing it again will not be enough. At least some of the information will still be on the storage device and could be found, for example, by using a disc recovery utility.

Suppose, for example, the file you’re erasing contains production passwords and needs to be deleted immediately after the present operation is complete.

Zero-filling the file once you’ve finished using it helps ensure the sensitive information is destroyed.

On a recent project we used the following code, which works well for small text files. It overwrites the existing contents with lines of zeros.

Note that zero-filling will not guarantee your security. If you’re really concerned, you’d be best to zero-fill and use a specialist utility like File Shredder or CCleaner to wipe clean the ’empty’ space on your drive.

Как очистить файл в python

В этом уроке мы разберем еще несколько команд в Питоне 2.7 для работы с файлами.

Это следующие команды:

read() – эта команда позволяет прочесть все содержимое того или иного файла. С данной командой мы уже встречались в предыдущем уроке.

readline — эта команда позволяет прочесть всего-лишь одну строку из того или иного файла.

close – эта команда сохраняет и закрывает файл. Работа этой команды аналогична нажатию в текстовом редакторе на Файл-Сохранить.

write() – эта команда производит запись данных в тот или иной открытый файл. Внимание: сначала необходимо открыть файл командой open. При этом если открыть файл в режиме ‘w’, то командой write файл перезапишется полностью. Если же открыть файл в режиме ‘a’, то командой write в файл просто добавится новый текст.

truncate – а эта команда производит очистку всего содержимого файла.

Напомню, что команду open() мы разобрали в прошлом уроке при открытии и чтении содержимого файла (перейти в урок 19).

Практический пример

Создаем на рабочем столе текстовый файл test16_text.txt и вписываем в него следующий текст:

Должно получиться как на этом фото:

Сохраняем текстовый файл в кодировке OEM 866. Это нужно для того, чтобы на экране выводились кириллические буквы, а не кракозябры. Как сохранить: в программе Notepad++ нажимаем вверху на: Кодировки — Кодировки -Кириллица — OEM 866 .

Теперь создаем на рабочем столе файл test16.py Пишем в него руками следующий программный код:

Краткое пояснение к коду.

В начале программы мы прописываем как обычно код для адекватного отображения кириллических символов.
Далее – как обычно – работа с переменной argv (более подробно работа с argv разбирается ЗДЕСЬ и ЗДЕСЬ).
Далее прописываем условия, которые предлагает команда пользователю в интерактивном режиме – стереть файл или не надо стирать.
Далее программа сама открывает файл test16_text.txt, очищает его от содержимого и предлагает пользователю вписать в него три новых строки с помощью команды raw_input () . Далее программа присваивает эти строки переменным, а потом эти переменные уже вписывает в файл с помощью команды write .
В конце программа сохраняет и закрывает файл с помощью команды close .

Теперь открываем программу PowerShell и прописываем команду: python desktop/test16.py desktop/test16_text.txt
Выполняем все действия, в том числе нажимаем клавишу Enter, чтобы до конца пройти все действия, предлагаемые программой. А также заполняем все три новых строки.

В итоге у вас должно получиться примерно как на этих картинках:

Открываем файл test16_text.txt на рабочем столе и видим следующий текст, что говорит о том, что Python таки записал в файл тот текст, что мы вводили в PowerShell.

Домашнее задание

  1. Внимательно пропишите каждую строку команды от руки, чтобы запомнить и пройти все действия в уме.
  2. Для каждой строки программы проговорите то действие, которое она выполняет, а лучше всего — напишите комментарий.
  3. Поразбирайтесь в коде, особенно в команде open() . Видите, мы открыли файл в режиме ‘w’ . При этом прописали ниже в коде команду truncate . Так ли она нужна в данном режиме? Попробуйте выполнить сценарий без нее.

В следующем уроке мы научимся копировать содержимое файлов — перейти в урок 21.

  • Вы здесь:  
  • Главная />
  • Python 2.7 с нуля />
  • Урок 20. Команды read, close, write, truncate для работы с файлами

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *