Overwrite file in Python

Python overwrite file

File Handling in Python

We can read and write content to files in Python. We use the open() function to create files and specify the path and mode for the required file. This creates a file handling object that handles different file operations.

Ways to overwrite file in Python

To overwrite a file, we need to delete its content. In this article, we will overwrite a file in Python.

Using the w parameter in the open() function

We can open the files in different modes. We have the write (w), read (r), and append (a) mode. When we open the file in the write mode, it removes all the previous contents of the file, and we can write data to this file.

For example,

Contents of the file:

Using the file.truncate() function

The truncate() function allows us to remove the contents of the file. For this, we need to ensure that the file pointer is at the start of the file. To achieve this, we use the file.seek() function and set the pointer to the start.

This method is suitable when we open the file in the read mode.

See the code below.

Contents of the file:

In the above example,

  • The r+ mode opens the file in reading and writing mode.
  • The f.seek(0) puts the file pointer to the start of the file.

Using the replace() function

The replace() function allows us to replace a given string with a different string. With this function, we can overwrite an existing file by replacing a specific phrase.

For example,

Contents of the file.

In the above code,

  • We first open the file in the read mode.
  • We read the contents of the file.
  • Then, we replace the required phrase from the contents using the replace() function.
  • We write this new data to the same file by opening it in the write mode, automatically removing its previous content.

Using the pathlib module

For users working with Python 3, the pathlib module can access files and read and write the contents. We can overwrite the contents and replace the contents of the file using the write_text() function and the re.sub() function. The re.sub() function replaces a string given it matches a regular expression pattern or not.

See the code below.

Contents of the file.

Let us understand what is happening in the above example.

  • We read the given file using its path and specifying it in the Path() function.
  • The read_text() stores its content in a variable.
  • We replace the string using the re.sub() function.
  • The write_text() writes the new file’s contents and removes its previous data.

Using the os.remove() function

If we wish to overwrite file, we can delete it and create a new file. To delete a file, we can use the os.remove() function.

We will first check whether a given file exists or not using the os.path.exists() function. If the file exists, we remove it using the os.remove() function.

After this, we create a new file of the same name and write data to it.

For example,

Contents of the file.

That’s all about how to overwrite file in Python.

Was this post helpful?

Related Posts

  • 21 December

    Save Object to File in Python

    Table of ContentsUse pickle.dump() FunctionUse dill.dump() FunctionUse pandas.to_pickle() Function Use pickle.dump() Function To save object to file in Python: Use the open() function with the with keyword to open the specified file. Use the pickle.dump() function to convert the object to a binary format to write it to the file. [crayon-63da7dbab8f38463567270/] [crayon-63da7dbab8f3e274800717/] Python’s pickle is […]

  • 18 December

    Write Binary File in Python

    Table of ContentsUse bytearray() FunctionUse bytes() FunctionUse struct.pack() FunctionUse encode() Function with join()Use to_bytes() Function Use bytearray() Function To write a binary file in Python: Use the bytearray() function to convert the list of bytes to a bytearray type object. Use a with clause with open() the method in write binary mode(wb) Use write() method […]

  • 26 November

    Remove Empty Lines from Text File in Python

    Table of ContentsUse isspace() MethodUse strip() MethodUse the FileInput() Method Use isspace() Method To remove empty lines from a Text File in Python: Open a file in read and write mode(r+). Use for loop for iterate over each line in the file. Use isspace() method to check if line is empty. if it is not […]

  • 16 November

    Create Temp File in Python

    Table of ContentsHow to Create Temp File in PythonUsing the tempfile.NamedTemporaryFile objectUsing the tempfile.TemporaryFile objectUsing the mkstemp() functionConclusion Sometimes applications require storage and processing of temporary data. For such purposes, Python provides the tempfile library that can be used to create such files and directories. How to Create Temp File in Python This tutorial will […]

  • 02 October

    Get Temp Directory in Python

    Table of ContentsGet Temp Directory in PythonUsing the tempfile.Gettempdir() Function to Get Temp Directory in PythonUsing the tempfile.Gettempdirb() Function to Get Temp Directory in PythonUsing the tempfile.Tempdir Variable to Get Temp Directory in PythonConclusion Sometimes we can encounter scenarios where we wish to store temporary data in Python. This can include situations of creating temporary […]

  • 19 May

    Remove Extension From Filename in Python

    Table of ContentsHow to Remove Extension From Filename in Python?Remove Extension From Filename in Python Using the os ModuleRemove Extension From Filename in Python using the pathlib moduleRemove Multiple File Extensions Using pathlib Module in PythonConclusion While programming in python, we often have to deal with file names. In this article, we will discuss how […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.