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:
- 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.
- 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:
- 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.
- Using files to extract data (input) while dealing with huge amounts of data, saves time.
- 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:
- 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.
- 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’.
- 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).
- 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 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:

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:

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:

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 :
- 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.
- 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:
- Path(): This function is imported from the pathlib module. It returns the path of a directory/file.
- write_text(): This function opens a file to read, writes text in it, and closes the file.
- 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!
Python – How to Replace String in File?
To replace a string in File using Python, follow these steps:
- Open input file in read mode and handle it in text mode.
- Open output file in write mode and handle it in text mode.
- For each line read from input file, replace the string and write to output file.
- Close both input and output files.
Examples
1. Replace a string in File
Consider that we have a text file with some spelling mistakes. And we have found that the string python is mis-spelled as pyton in the file.
In the following example, we will replace the string pyton with python in data.txt file, and write the result to out.txt.
Python Program
What have we done here?
- Open data.txt in read text rt mode and get the reference to fin.
- Open out.txt in write text wt mode and get the reference to fout.
- for line in fin :for each line in fin i.e., data.txt, line.replace(): replaces string pyton with python and fout.write: writes to out.txt.
- fin.close(): closes the file referenced by fin, fout.close(): closes the file referenced by fout.
Input File
Output File
The string pyton in the file is replaced with the string python.
2. Replace string and update the original file
In the following example, we will replace the string pyton with python in data.txt file, and overwrite the data.txt file with the replaced text.
Python Prgoram
What have we done here?
- Open file data.txt in read text mode rt.
- fin.read() reads whole text in data.txt to the variable data.
- data.replace() replaces all the occurrences of pyton with python in the whole text.
- fin.close() closes the input file data.txt.
- In the last three lines, we are opening data.txt in write text wt mode and writing the data to data.txt in replace mode. Finally closing the file data.txt.
Input File
The same input file after program execution.
Summary
In this tutorial of Python Examples, we learned to replace a string with other in file, with help of well detailed examples.
Заменить строку в файле с помощью Python

Работа с файлами — важный аспект любого веб-приложения. Python, как и другие языки программирования, поддерживает обработку файлов. Это позволяет программистам иметь дело с файлами и, по сути, выполнять некоторые базовые операции, такие как чтение, запись и некоторые другие параметры обработки файлов для работы с файлами.
Функцию open() можно использовать для открытия файла в программе Python. Файл можно открыть в текстовом или двоичном режиме, который выбирает пользователь. Функция open() имеет несколько режимов, каждый из которых обеспечивает различные варианты доступа к открываемому файлу.
Термин String в Python можно описать как набор символов Unicode, заключенных в одинарные или двойные кавычки. Строки могут содержаться внутри текстовых файлов, которые должны открываться в коде Python.
В этом руководстве будут рассмотрены различные методы замены строки в файле на Python.
Please enable JavaScript
Используйте функцию replace() , когда входные и выходные файлы различаются
Метод replace() в Python используется для поиска подстроки и замены ее другой подстрокой.
Функция replace() имеет три параметра, а именно newvalue , oldvalue и count . И oldvalue , и newvalue являются обязательными значениями, и предоставление функции с параметром count необязательно.
В следующем коде используется функция replace() для замены строки в Python, когда входные и выходные файлы различаются.
В выводе приведенного выше кода строка gode в файле будет заменена словом God .
В приведенном выше коде мы одновременно работаем с двумя разными файлами: f1.txt и f2.txt . f1.txt открывается в режиме чтения текста rt и ссылается на end . f2.txt открывается в режиме записи текста wt и ссылается на fout . Затем цикл for повторяется, и при каждом появлении в файле строки gode она заменяется словом God . Затем оба файла закрываются после необходимых операций с помощью функции close() .
Используйте функцию replace() , когда для ввода и вывода используется только один файл
В этом методе один и тот же файл используется как для ввода, так и для вывода.
Здесь мы используем оператор with вместе с функцией replace() . Менеджер контекста with выполняет фундаментальную функцию: делает программу короче и читабельнее.
Когда мы используем оператор with с обработкой файлов, файл, который мы открыли в коде Python, не нужно закрывать вручную; он автоматически закрывается после завершения блока with .
Следующий код использует функцию replace() для замены строки в Python, когда входной и выходной файл совпадают.
Следующий код принимает file1 как входной и выходной файл. Сначала файл открывается в режиме чтения текста rt , а содержимое файла считывается и сохраняется в переменной. Затем файл закрывается и открывается снова, но уже в режиме записи текста wt . Строка заменяется, и данные записываются в этом режиме, а затем файл закрывается.
Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.
Как заменить строчку в .txt файле через python 3?
В файле есть определенная строка, ее сначала выводит цикл на экран, всю строку, а потом нужно бы ее изменить, т.е. удалить старое и написать на ней новое, как это делается?
Замену можно сделать так:
Открыть файл на чтение можно либо так
Преимущество второго способа в том, что вам не надо закрывать файл вручную. Конструкция with сделает это за вас после закрытия её блока.
Перезаписать файл можно же таким образом:
Но так как вы хотите писать файл с заменой строки, то вам нужно воспользоваться перебором по readlines() и либо регулярными выражениями, либо сравнением текущей строки с той, которую вы ищите (если у вас есть искомая строка, конечно) и её заменой.
Грубо говоря, вы можете сделать это как-то так:
Также могут помочь функции startswith() и endswith() , если у вас есть только начало или конец от искомой строки. И помните про регистр!
Также можно не перебирать строки, а обратиться к строке по индексу, если вам известно какой у неё номер, и заменить её содержание.
И можно воспользоваться функцией replace() , как уже написал автор второго ответа, что сократит количество кода, но заменит абсолютно все вхождения. Чтобы этого избежать, при вызове функции можно указать максимальное число совершаемых замен: S.max(sub_in_str, to_change_str, max) .
Также учитывайте, что replace() совершит замену даже если строка частично совпадает. То есть выполнив это:
Мы получим Thwas was a simple example
Если длина новой строки не совпадает с длиной старой, то придётся переписать весь файл (начиная со строчки, которую вы хотите заменить) даже если вам надо заменить только одну строку в файле (за редкими исключениями). Связанный вопрос: Запись текстовой строки по нужному индексу в файл на языке Си?
Чтобы в случае ошибки сохранить оригинал или для больших файлов (когда всё содержимое в памяти не помещается), может использоваться временный файл куда новое содержимое пишется и в конце в случае успеха он переименовывается в исходное имя файла. Похожий подход использует стандартный модуль fileinput : исходный файл переименовывается (чтобы из него читать текущее содержимое), а стандартный вывод перенаправляется в указанный файл (простой print печатает прямо в файл):
Можно самостоятельно явно временный файл создать:
Отличие в том, что оригинальное содержимое хранится в .bak файле в fileinput подходе, а в коде с NamedTemporaryFile исходный файл заменяется только в случае успеха (в отсутствие исключений).
Небольшой файл можно в память целиком загрузить, чтобы получить список строк, изменить нужные и целиком перезаписать этот файл, рискуя потерять данные, если ошибка возникнет при записи (аналогично коду в @stxdtm ответе):
Подробнее представленные подходы можно по ссылкам в похожем ответе посмотреть.
Если длина новой строки совпадает с длиной старой (в байтах), то можно прямо по месту изменения делать, не переписывая другие части файла, к примеру, используя mmap модуль, который позволяет файл рассматривать и как файл ( .readline() , etc), и как байтовую строку ( .find() , можно применять регулярные выражения). Связанный вопрос: Python — How can I change bytes in a file.