Как перезаписать файл в python
Перейти к содержимому

Как перезаписать файл в python

  • автор:

How to Overwrite a File in Python? (5 Best Methods with Code)

How to Overwrite a File in Python? (5 Best Methods with Code)

File Handling is an essential component of programming. Files are used to store data permanently. Python provides a method for storing program data and performing operations on it. Opening, writing, reading, closing, overwriting, and appending files are a few examples of these operations.

In this article, you’ll learn about various file-handling operations, focusing on how to overwrite a file in Python.

Before proceeding forward, let’s look at the fundamentals!

What is a File in Python?

A file is a collection of data stored as a unit on the disk. It is identified by its file name and file extension. Everything is stored in the form of a file, be it excel sheets, documents, or more.

We generally deal with two types of Files in Python:

  1. Binary File: As the name suggests, these files store binary data (like audio files, images, and videos). These are not human-readable and are generated for machine interpretations.
  2. Text File: These files store data in human-readable form, each new line ending with a newline character (\n). This is used to store ‘character data’.

In this article, we’ll focus on text files.

You must be wondering, what is the need for Files in Python?

Need for Files in Python

Here are a few reasons highlighting the need for files while programming:

  1. Storing data in a file preserves it even after the termination of the program. Hence, it may store the input, computations, or output, as per commands.
  2. Using files to extract data (input) while dealing with huge amounts of data, saves time.
  3. It is easy to relocate computational data through files.

Now, that you’ve learned about files and why we need them, let’s take a look at File Operations.

File Operations in Python

File operations are the operations that can be performed on a file. These include operations carried out by the user using Python commands (or any other programming language).

A few fundamental file operations are listed below:

  1. Open: The first and most important operation on a file is to open it. When you create a file, you must open it in order to do further file processing operations. Python offers an in-built open() function to open a file. The open() function returns a file object, also known as a handle, to perform further operations accordingly.
  2. Read: As the name suggests, this operation reads the content of a file. Python provides various methods to read a file, the most common being the read() function. Note that in order to read a file you’ll need to open that file in ‘read mode’.
  3. Write: This operation is used to write information into a file. There are various modes, that can be used, for the write operation (we’ll soon discuss the different modes).
  4. Close: After completing all procedures, the file must be closed in order to save the data. This operation frees up all the resources used up by the file while processing. Python has a close() method to close the file.

You’re probably wondering why you need to manually close the file. Isn’t Python’s Garbage Collector capable of performing the task?

The Garbage Collectors clean up unreferenced objects. You should not rely on a garbage collector to close the file. It could result in data loss or error. To learn more about Garbage Collectors, see Delete a Variable in Python.

Take a look at the below for a few other file operations:

file operations in python

File Access Modes in Python

These specify how the file will be used after it is opened. File access modes regulate the type of activities that can be performed on a file. More specifically, they specify the position of a «file handler».

A File Handler is like a pointer that indicates the position from where data should be read or written in a file. You can also assume it is a cursor, for better understanding.

File Access Modes are important to learn since they play a major role while dealing with files. They tell accessibility to the file while performing any file operation. So, before moving on to overwriting a file in Python, let’s get a better understanding of file access modes in Python.

Python has six File Access Modes. They are as follows:

Access Mode

(File Operations)

Default mode. Opens a file in Python to read. (Raises an I\O error if the file does not exist.)

The access methods are mentioned along with the file name in the open() function.

The syntax to open a file is:

f = open(«FilePath», «access mode»)

The file could be in the same or a different directory. As a result, you must take it into account while specifying the file location. It might be either an Absolute Path (starting from the root directory) or a Relative Path (lies in the same folder).

Let’s take an example of how to open a file in Python:

(Note: I’ve created a file «favtutor.txt» in the same directory as my Python file (temp.py))

Note that the file handler ‘f’ calls out the read() method to read (obtain) the lines from the file.

Output:

You’ll notice that the file «favtutor.txt» was created before we called out the open() function. Let’s try opening another (non-existing) file in Python:

Output:

It produces an error indicating the absence of any file named ‘abc.txt’.

Try opening the file using «write-only» mode. You’ll notice the basic difference between read-only and write-only modes.

While the first generated an error on a non-existing file, the latter will create a file by the command.

Now that we’ve learned some basics of File Handling in Python, let’s move on to the file operation — «overwriting» a file in Python.

What is Overwriting a File in Python?

Overwriting is the process of replacing old data with new data. It involves altering the pre-written data in a file. Overwriting a file can be understood as deleting an existing file and replacing it with a new one with the same name.

You must not confuse ‘overwriting’ and ‘deleting’ a file in Python with the same operations.

A deleted file can be recovered from the computer’s memory, however, an overwritten file cannot. This occurs because an overwritten file replaces the original content of that file, causing the file to alter physically. As a result, retrieving data in this circumstance has less probability.

Refer to the image below for a better understanding of Overwriting a File in Python:

overwrite a file in python

Before moving on to ways to overwrite a file in Python, remember that sometimes «overwriting a file in Python» is considered similar to «replacing a few lines in a file». But it is different from appending data in a file.

How to Overwrite a File in Python?

The need to overwrite often occurs when you need to completely alter a file in Python. The below methods contain both, methods to overwrite the complete file, as well as, methods to overwrite a few lines in Python.

So, let’s get started!

01) Using write only (‘w’) File Access Mode

The ‘write only’ (‘w’) File Access Mode allows you to only write in the file. (Remember to specify the file access mode in the open() function.) Python includes the write function for writing to a file.

If the file contains any content, it will be completely overwritten by anything you write on the opened file. All the previous data in the file will be lost, and can’t be recovered in many cases when you overwrite a file using this method.

Let’s take an example to understand it better.

Consider overwriting a file called favtutor.txt. That file must be opened in write mode and assigned to file handler ‘f.’ The file handler ‘f’ can be used to perform the write() operation.

Here’s a snapshot of the already existing file:

snapshot of file

Overwriting the file in Python:

Since we cannot read the file (as it is in write-only mode), here’s a snapshot of the file after overwriting-

Output:

overwrite file in python

Using the write-only access mode is the simplest way to overwrite a file in Python.

02) Using os.remove() function

This is another method to overwrite a complete file in Python. This includes deleting the existing file and creating a new file with the same credentials. While it indirectly overwrites the file, it isn’t recommended to use this method often. This might change the inode number of the file.

Inodes store information about files and directories (folders), such as file ownership, access mode (read, write, execute permissions), and file type. Each file is connected with an inode, which is identifiable by an integer known as an i-number or inode number.

Note that this requires importing the os module.

Let’s try removing a file (abc.txt) in Python to overwrite it.

Output:

The file abc.txt doesn’t exist, hence we encounter an error on trying to remove that. Before removing a file, you should check whether the file exists or not. If the file doesn’t exist, it will produce an error. Hence, to check whether the file exists or not, the os module has os.path.exists() function.

(Again on a file that does not exist!) Example:

Output:

The if-else block saves us from encountering an error. We can also open the file using ‘w+’ or ‘w’ access modes in the else block. These modes create a new file if the file doesn’t exist.

Now, let’s take an example of overwriting an existing file in Python using os.remove() function:

Output:

I’ve opened the file at the end to read the content of the file. Note that you need to close and open a file again in order to change its access mode.

03) Using seek() and truncate() function

This method can be used to overwrite a file (completely or a particular line) in Python. This method involves two functions :

  1. The seek() function: This function sets the handler (pointer) at the beginning of the file. This is called upon to ensure that the handler stays at the start of the file, hence by default it is set at 0.
  2. The truncate() function: This function removes the data of the file.

While calling upon the seek() function, you can add your data to the file using the write() function, and then truncate the file at the end.

Output:

Note that the file is overwritten by new data.

04) Using replace() method

This method comes under overwriting a specific phase in an existing file. Partially, this method of overwriting a file in Python involves the use of the ‘write only’ mode. Here, we store the data in another variable, making a few replacements in it, using replace() method. This new variable is then called upon to overwrite the file.

Firstly, you need to read the file in order to store the data in another variable (here, variable named content). Then replace() method is applied to the stored data. This method requires sequence matching in order to replace the existing data with another.

Output:

Note how the words «File» is ‘overwritten’ by «Data». The above method also answers the question — «How to replace a string in a file in Python? «

05) Using re.sub() function

This is another way of overwriting a file in Python. It is similar to replacing data in a file. This method requires the sub() function of the Regular Expression module (re module). Recall that the sub() function returns a string in which the replace string replaces all matching occurrences of the given pattern. Hence, this also sequentially matches the characters to find a match.

You’ll also encounter some new functions here:

  1. Path(): This function is imported from the pathlib module. It returns the path of a directory/file.
  2. write_text(): This function opens a file to read, writes text in it, and closes the file.
  3. read_text(): This function opens a file, reads it, and closes it.

So, the write_text() and read_text() functions don’t need to declare commands to open or close the file separately.

Let’s take an example to overwrite a file in Python using re module:

Output:

Note that the data (string here) is case-sensitive. Since the sub() function matches the text, it only overrides ‘file’ and not ‘File’ in the above example.

Conclusion

In this article, we’ve talked about some of the easiest ways to overwrite a file in Python. Apart from the above methods, there is another method to overwrite a file in Python.

It requires relocating a file (say abc.txt) to a directory having a file of the same name (abc.txt, the file to be overwritten). This method uses the shutil module. Though it is not recommended, since it’s basically replacing a file with another with the help of default naming conventions in a computer.

Though I’ve mostly used ‘read only’ and ‘write only’ modes, you should try these methods with other file access modes. You might get surprised by the output. Happy Coding!

click fraud protection

Мы рассмотрим все способы. Реализуйте какое-то действие и измените его, а затем перезапишите его совершенно новыми данными. Давайте приступим к реализации и выполнению действительного примера. Эти методы следующие:

  1. Метод Open()
  2. Метод усечения()
  3. Метод замены()
  4. Метод Os.remove()
  5. Шутиль. Метод Переместить()

Пример 1: Использование метода open() для перезаписи файла.

Метод open() принимает в качестве аргумента два параметра: путь к файлу и режим, либо это может быть режим чтения «r» или режим записи «w». Чтобы перезаписать файл, чтобы записать новое содержимое в файл, мы должны открыть наш файл в режиме «w», который является режимом записи. Сначала он удалит существующий контент из файла; затем мы можем написать новый контент и сохранить его.

У нас есть новый файл с именем «myFile.txt». Во-первых, мы откроем файл в методе open(), который принимает имя файла или путь и добавляет некоторый контент в файл с режимом «a», который является режимом добавления; он добавит содержимое в файл.

Для записи некоторого содержимого в файл мы должны использовать метод myFile.write(). После этого мы открываем и читаем файл в режиме «r». Мы можем получить содержимое файла с помощью оператора печати.

мой файл. записывать ( «Это мой файл с некоторым содержимым!» )

мой файл. близко ( )

мой файл = открытым ( «мой файл1.txt» , «р» )

Распечатать ( мой файл. читать ( ) )

Это результат добавления и чтения содержимого файла. Под скриншотом вы можете увидеть содержимое файла.

Теперь мы используем режим «w» для перезаписи существующего содержимого новым и открытия файла с помощью метода open () вместе с режимом «r» для чтения нового содержимого в файле.

мой файл. записывать ( «Это мой файл с новым содержанием!. Мы удалили предыдущую» )

мой файл. близко ( )

мой файл = открытым ( «мой файл1.txt» , «р» )

Распечатать ( мой файл. читать ( ) )

Вот вывод нового содержимого в файле «myFile.txt».

Пример 2: Использование метода truncate() для перезаписи файла.

Этот метод truncate() позволяет нам удалить данные файла. Для этого мы должны использовать функцию seek(). Этот метод, который устанавливает указатель в начале файла, по умолчанию установлен в ноль. Используя эту функцию, мы можем записать новый контент и обрезать старый.

Теперь у нас есть еще один пример того, как метод truncate() обрезает содержимое в существующем файле. Мы открываем файл myFile1.txt в режиме записи, вызываем функцию seek(), установленную на нулевой указатель, и пишем новый контент в write().

Затем, чтобы прочитать файл с новым содержимым, мы должны использовать «r» и отобразить функцию print(), в которой хранится myFile2.read(), через которую мы можем прочитать новое содержимое.

мой файл2. стремиться ( 0 )

мой файл2. записывать ( «Новый контент с использованием метода truncate()» )

мой файл2. обрезать ( )

мой файл2 = открытым ( «мой файл1.txt» , «р» )

Распечатать ( мой файл2. читать ( ) )

Выходные данные отображают новое содержимое на экране консоли ниже.

Пример 3: Использование метода replace()

Далее идет метод replace(), который перезаписывает данную строку, заменяя ее другой строкой. Мы можем записать новое содержимое в существующий файл, открыв его в режиме записи «w», изменив содержимое строки и автоматически удалив предыдущее содержимое в файле.

Ниже приведен пример, который заменит строку «контент» на «информацию» с помощью функции new_content.replace() на переменную «myFile3», которую мы прочитаем в функции печати.

новый_контент = мой файл. читать ( )

новый_контент = новый_контент. заменять ( ‘содержание’ , ‘Информация’ )

мой файл. близко ( )

мой файл3 = открытым ( ‘мой файл1.txt’ , ‘ж’ )

мой файл3. записывать ( новый_контент )

мой файл3 = открытым ( «мой файл1.txt» , «р» )

Распечатать ( мой файл3. читать ( ) )

Вывод строки замены показан ниже:

Пример 4: Использование метода os.remove() для перезаписи файла.

Вот способ перезаписать файл; если мы хотим создать новый файл. Для этого нам нужно удалить предыдущий файл. Мы должны вызвать метод os.remove(). Он удалит или удалит путь к файлу.

Для этого сначала мы должны проверить, существует ли файл или это действительный файл через is. Дорожка. Exist(), потому что OsError возникает, если файл не существует или это может быть недопустимое или недоступное имя файла или путь.

Давайте запустим пример кода того, как работает метод os.remove(). Во-первых, нам нужно импортировать модуль os, затем у нас есть условный оператор, чтобы проверить, существует ли файл или нет. В этом случае у нас есть существующий файл, поэтому os.remove() удалит в нем текст файла. С помощью File_new.write() мы можем написать новый контент. Затем режим чтения покажет нам новый контент.

если ( Операционные системы . дорожка . существует ( «pythonFile.txt» ) ) :

Операционные системы . Удалить ( «pythonFile.txt» )

Распечатать ( «Файл не найден» )

file_new = открытым ( «pythonFile.txt» , «ж» )

файл_новый. записывать ( ‘Мой новый контент о методе os.rmeove()’ )

file_new = открытым ( «Файл_Новый.txt» , «р» )

Распечатать ( файл_новый. читать ( ) )

Как видите, предыдущее содержимое было удалено, и у нас есть вывод только что созданного содержимого.

Пример 5: Использование метода Shutil.move() для перезаписи файла.

Если мы хотим переместить файл в каталог, в котором присутствует существующий файл с таким же именем, у нас будет Shutil. Метод move() можно реализовать, импортировав модуль Shutil.

Shutil.move() перезаписывает место назначения файла новым исходным файлом. Для этого мы передали «src» и «dst» в качестве аргумента в метод Shutil.move () как Shutil. двигаться (источник, дст). Это переместит исходный файл «src» в место назначения «dst». Возвращаемое значение этого метода — строка, представляющая путь к только что созданному файлу.

Чтобы переместить файл в новый каталог, нам нужно импортировать библиотеку Shutil. После этого мы назначили исходный путь в «my_source» и путь назначения в «my_destination». os.path.basename() получит имя файла, а через os.path.join() это будет имя файла пути назначения. Метод Shutil.move() примет my_source и dest_path в качестве аргументов и переместит файлы.

импорт Операционные системы

мой_источник = «с: \\ пользователи \\ л.с. \\ Рабочий стол \\ картинки \\ корабль.jpg»

my_destination = «Ф: \\ Данные рабочего стола \\ статья_python»

my_filename = Операционные системы . дорожка . базовое имя ( мой_источник )

путь_назначения = Операционные системы . дорожка . присоединиться ( my_destination , my_filename )

шутил . переехать ( мой_источник , путь_назначения )

Распечатать ( «Текущий источник для перемещения» , мой_источник )

Распечатать ( «Новый путь назначения:» , путь_назначения )

Как видите, текущий исходный файл «ship.jpg» переместился на новый путь назначения. Отображение вывода ниже:

Заключение

Мы рассмотрели различные методы перезаписи файла в python с реализацией простых примеров, которые легко понять. Эта статья поможет вам эффективно и профессионально справиться с перезаписью файлов.

Overwrite a file in Python

The term “file” refers to a named location on a disk that stores data. Python has various functions and methods to work with files. “Overwriting” a file means changing its data with updated information, as per the requirements which is essential while dealing with records. Throughout this article, we will explore several ways to overwrite a file in Python.

The below methods are available to overwrite a Python file:

Before overwriting a file, let’s take a look at the file that is going to be overwritten in this blog:

Method 1: Overwriting a File Using “write()” Method

In Python, to overwrite a file the “write()” method is utilized after opening the file in write mode. This method replaces the existing content with the new data.

Example

In the above code, the “write()” method overwrites the text file named “filename.txt” content with the new string values. The newline character “\n” is used in between the strings to move the cursor to a new line.

Output

The specified file has been successfully overwritten.

Method 2: Overwriting a File Using “truncate()” Method

The “truncate()” method can also be utilized to overwrite a file. It removes all the content after a specified position, including that position. Here’s how to use it:

Example

The below code is used to overwrite the file:

The above code first opens the file in read-write (“r+”) mode and then uses the “truncate()” method to remove all the existing content. Finally, the “write()” method writes the new specified data to the file.

Output

The specified file has been overwritten accordingly.

Method 3: Overwriting a File Using Mode “w”

The mode “w” is used to overwrite a file by writing to a file by modifying the existing file content.

Example

Here is an example code:

In the above code snippet, the discussed file “filename.txt” is opened in write mode and the stated new data is written to it. The added “with” statement is used to automatically close the file.

Output

The file has been successfully overwritten in the above outcome.

Method 4: Overwriting a File Utilizing “shutil” Module

The “shutil” module delivers a high-level interface for manipulating files and directories. The “copyfile()” method of this module is also used to overwrite a file. This method copies the contents of the original file to the destination file and overwrites it if it already exists.

The file and the content that is going to be copied are shown below:

Example

The below code copies the content of one file and overwrites it to another:

This code imports the “shutil” module and copies the contents of “newfile.txt” to “filename.txt” and overwrites it if the content already exists.

Output

In the output snippet, the specified file has been successfully overwritten.

Method 5: Overwriting a File Using “os” Module

The “os” module can be utilized to interact with the operating system. The “remove()” method of this module is used to delete the existing file and then create a new file with the same name to overwrite it.

Example

Let’s overview the following code:

The above code block removes the existing “filename.txt” and then creates a new file with the same name and writes the new data to it.

Output

As a result of the above code, the overwriting file has been completed.

Method 6: Overwriting a File Using “pathlib” Module

The “pathlib” module provides an object-oriented way to interact with the file system. The module’s “write_text()” method is used to write the new data to a file and overwrite the existing content.

Example

Let’s go through the following example code:

This code uses the “Path()” function to create a Path object and then uses the “write_text()” method to write the new data to the file, thereby overwriting the existing content.

Output

The above output verified that the particular file has been overwritten with new data.

Conclusion

Python has several methods for overwriting files such as the “write()” method, “truncate()” method, mode “w”, “shutil” module, “os” module, or the “pathlib” module. These methods are explained in this blog post using appropriate examples to overwrite a file in Python.

About the author

Talha Saif Malik

Talha is a contributor at Linux Hint with a vision to bring value and do useful things for the world. He loves to read, write and speak about Linux, Data, Computers and Technology.

Overwrite a File in Python

Overwrite a File in Python

This tutorial will demonstrate various methods to overwrite a file in Python. We will look into methods to write new text by deleting the already saved text and how we can first read the data of the file, apply some actions and changes on it, and then overwrite it on the old data.

Overwrite a File in Python Using the open() Function

The open(file, mode) function takes file (a path-like object) as input and returns a file object as output. The file input can be a string or bytes object and contains the file path. The mode is the mode we want to open the file in; it can be r for the read mode, w for the write or a for the append mode, etc.

To overwrite a file and write some new data into the file, we can open the file in the w mode, which will delete the old data from the file.

If we want first to read the data save in the file and then overwrite the file, we can first open the file in reading mode, read the data, and then overwrite the file.

Overwrite a File in Python Using the file.truncate() Method

Since we want to read the file data first and then overwrite it, we can do so by using the file.truncate() method.

First, open the file in reading mode using the open() method, read the file data and seek to the start of the file using the file.seek() method, write the new data and truncate the old data using the file.truncate() method.

The below example code demonstrates how to overwrite the file using file.seek() and file.truncate() methods.

Syed Moiz is an experienced and versatile technical content creator. He is a computer scientist by profession. Having a sound grip on technical areas of programming languages, he is actively contributing to solving programming problems and training fledglings.

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

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