• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Overwrite a File in Python

Overwrite a File in Python

Author: Aditya Raj
Last Updated: March 13, 2023

File handling is one of the first tasks we do while working with data in python. Sometimes, we need to change the contents of the original file or completely overwrite it. This article discusses different ways to overwrite a file in python.

Table of Contents
  1. Overwrite a File Using open() Function in Write Mode
  2. Using Read Mode and Write Mode Subsequently
  3. Overwrite a File Using seek() and truncate() Method in Python
  4. Conclusion

Overwrite a File Using open() Function in Write Mode

To overwrite a file in python, you can directly open the file in write mode. For this, you can use the open() function. The open() function takes a string containing the file name as its first input argument and the python literal “w” as its second input argument.

If the file with the given name doesn’t exist in the file system, the open() function creates a new file and returns the file pointer. If the file is already present in the system, the open() function deletes all the file contents and returns the file pointer. 

Once we get the file pointer, we can write the new data to the file using the file pointer and the write() method. The write() method, when invoked on the file pointer, takes the file content as its input argument and writes it to the file. Next, we will close the file using the close() method. After this, we will get the new file with overwritten content.

For instance, suppose that we want to overwrite the following text file in python.

Sample text file
Sample text file

To overwrite the above file, we will use the following code.

file=open("example.txt","w")
newText="I am the updated text from python program."
file.write(newText)
file.close()

The text file after execution of the above code looks as follows.

In this example, we have directly opened the text file in write mode. Due to this, the original content of the file gets erased. After this, we have overwritten the file using new text and closed the file using the close() method.

Using Read Mode and Write Mode Subsequently

In the above example, we cannot read the original file contents. If you want to read the original file contents, modify it and then overwrite the original file, you can use the following steps.

  • First, we will open the file in read mode using the open() function. The open() function will return a file pointer after execution. 
  • Then, we will read the file contents using the read() method. The read() method, when invoked on the file pointer, returns the file contents as a string. 
  • After reading the file contents, we will close the file using the close() method. 
  • Now, we will again open the file, but in write mode. 
  • After opening the file in write mode, we will overwrite the file contents using the write() method. 
  • Finally, we will close the file using the close() method.

After executing the above steps, we can overwrite a file in python. You can observe this in the following example.

file=open("example.txt","r")
fileContent=file.read()
print("The file contents are:")
print(fileContent)
file.close()
file=open("example.txt","w")
newText="I am the updated text from python program."
file.write(newText)
file.close()

Output:

The file contents are:
This a sample text file created for pythonforbeginners.

In this example, we first opened the file in read mode and read the contents as shown above. Then, we overwrote the file contents by opening it again in write mode. After execution of the entire code, the text file looks as shown below.

Modified text file
Modified text file

Although this approach works for us, it is just a workaround. We aren’t actually overwriting the file but reading and writing to the file after opening it separately. Instead of this approach, we can use the seek() and truncate() methods to overwrite a file in python. 

Overwrite a File Using seek() and truncate() Method in Python

To overwrite a file in a single step after reading its contents, we can use the read(), seek() truncate() and write() methods.

  • When we read the contents of a file using the read() method, the file pointer is moved to the end of the file. We can use the seek() method to again move to the start of the file. The seek() method, when invoked on the file pointer, takes the desired position of the file pointer as its input argument. After execution, it moves the file pointer to the desired location. 
  • To remove the contents of the file after reading it, we can use the truncate() method. The truncate() method, when invoked on a file pointer, truncates the file. In other words, it removes all the file contents after the current position of the file pointer.

To overwrite a file in python using the seek() and truncate() methods, we can use the following steps.

  • First, we will open the file in append mode using the open() function. 
  • Next, we will read the file contents using the read() method. 
  • After reading the file contents, we will move the file pointer to the start of the file using the seek() method. For this, we will invoke the seek() method on the file pointer with 0 as its input. The file pointer will be moved to the first character in the file.
  • Next, we will use the truncate() method to delete all the contents of the file.
  • After truncating, we will overwrite the file with new file contents using the write() method.
  • Finally, we will close the file using the close() method.

After executing the above steps, we can easily overwrite a file in python. You can observe this in the following example.

file=open("example.txt","r+")
fileContent=file.read()
print("The file contents are:")
print(fileContent)
newText="I am the updated text from python program."
file.seek(0)
file.truncate()
file.write(newText)
file.close()

Output:

The file contents are:
This a sample text file created for pythonforbeginners.

After execution of the above code, the text file looks as follows.

Conclusion

In this article, we discussed different ways to overwrite a file in python. To learn more about python programming, you can read this article on how to convert a pandas series into a dataframe. You might also like this article on how to read a file line by line in python.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us