{"id":18195,"date":"2021-11-06T15:07:48","date_gmt":"2021-11-06T09:37:48","guid":{"rendered":"https:\/\/java2blog.com\/?p=18195"},"modified":"2021-11-06T15:11:07","modified_gmt":"2021-11-06T09:41:07","slug":"python-overwrite-file","status":"publish","type":"post","link":"https:\/\/java2blog.com\/python-overwrite-file\/","title":{"rendered":"Overwrite file in Python"},"content":{"rendered":"<div id=\"toc_container\" class=\"toc_light_blue no_bullets\"><p class=\"toc_title\">Table of Contents<\/p><ul class=\"toc_list\"><li><a href=\"#File_Handling_in_Python\">File Handling in Python<\/a><\/li><li><a href=\"#Ways_to_overwrite_file_in_Python\">Ways to overwrite file in Python<\/a><ul><li><a href=\"#Using_the_w_parameter_in_the_open_function\">Using the w parameter in the open() function<\/a><\/li><li><a href=\"#Using_the_filetruncate_function\">Using the file.truncate() function<\/a><\/li><li><a href=\"#Using_the_replace_function\">Using the replace() function<\/a><\/li><li><a href=\"#Using_the_pathlib_module\">Using the pathlib module<\/a><\/li><li><a href=\"#Using_the_osremove_function\">Using the os.remove() function<\/a><\/li><\/ul><\/li><\/ul><\/div>\n<h2><span id=\"File_Handling_in_Python\">File Handling in Python<\/span><\/h2>\n<p>We can read and write content to files in Python. We use the <code>open()<\/code> 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.<\/p>\n<h2><span id=\"Ways_to_overwrite_file_in_Python\">Ways to overwrite file in Python<\/span><\/h2>\n<p>To overwrite a file, we need to delete its content. In this article, we will overwrite a file in Python.<\/p>\n<h3><span id=\"Using_the_w_parameter_in_the_open_function\">Using the <code>w<\/code> parameter in the <code>open()<\/code> function<\/span><\/h3>\n<p>We can open the files in different modes. We have the write (<code>w<\/code>), read (<code>r<\/code>), and append (<code>a<\/code>) 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. <\/p>\n<p>For example,<\/p>\n<pre code = \"python\">\nwith open('file.txt','w') as f:\n    f.write(\"New Content\")    \n<\/pre>\n<p>Contents of the file:<\/p>\n<pre>\nNew Content    \n<\/pre>\n<h3><span id=\"Using_the_filetruncate_function\">Using the <code>file.truncate()<\/code> function<\/span><\/h3>\n<p>The <code>truncate()<\/code> 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 <code>file.seek()<\/code> function and set the pointer to the start.<\/p>\n<p>This method is suitable when we open the file in the read mode.<\/p>\n<p>See the code below.<\/p>\n<pre code = \"python\">\nwith open('file.txt','r+') as f:\n    f.seek(0)\n    f.write(\"New Content\")\n    f.truncate()    \n<\/pre>\n<p>Contents of the file:<\/p>\n<pre>\nNew Content    \n<\/pre>\n<p>In the above example, <\/p>\n<ul>\n<li>The <code>r+<\/code> mode opens the file in reading and writing mode.<\/li>\n<li>The <code>f.seek(0)<\/code> puts the file pointer to the start of the file.<\/li>\n<\/ul>\n<h3><span id=\"Using_the_replace_function\">Using the <code>replace()<\/code> function<\/span><\/h3>\n<p>The <code>replace()<\/code> 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.<\/p>\n<p>For example,<\/p>\n<pre code = \"python\">\nf1 = open('myfile.txt','r')\ndata = f1.read()\ndata = data.replace('abc','def')\nf1.close()\nf2 = open('myfile.txt','w')\nf2.write(data)\nf2.close()    \n<\/pre>\n<p>Contents of the file.<\/p>\n<pre>\nreplaced string def    \n<\/pre>\n<p>In the above code,<\/p>\n<ul>\n<li>We first open the file in the read mode. <\/li>\n<li>We read the contents of the file.<\/li>\n<li>Then, we replace the required phrase from the contents using the <code>replace()<\/code> function.<\/li>\n<li>We write this new data to the same file by opening it in the write mode, automatically removing its previous content.<\/li>\n<\/ul>\n<h3><span id=\"Using_the_pathlib_module\">Using the <code>pathlib<\/code> module<\/span><\/h3>\n<p>For users working with Python 3, the <code>pathlib<\/code> module can access files and read and write the contents. We can overwrite the contents and replace the contents of the file using the <code>write_text()<\/code> function and the <code>re.sub()<\/code> function. The <code>re.sub()<\/code> function replaces a string given it matches a regular expression pattern or not.<\/p>\n<p>See the code below.<\/p>\n<pre code = \"python\">\nimport re\nfrom pathlib import Path\nfilepath = Path(\"myfile.txt\")\ndata = filepath.read_text()\nfilepath.write_text(re.sub(r\"def\",r\"abc\", data))    \n<\/pre>\n<p>Contents of the file.<\/p>\n<pre>\nreplaced string abc    \n<\/pre>\n<p>Let us understand what is happening in the above example.<\/p>\n<ul>\n<li>We read the given file using its path and specifying it in the <code>Path()<\/code> function.<\/li>\n<li>The <code>read_text()<\/code> stores its content in a variable.<\/li>\n<li>We replace the string using the <code>re.sub()<\/code> function.<\/li>\n<li>The <code>write_text()<\/code> writes the new file&#8217;s contents and removes its previous data.<\/li>\n<\/ul>\n<h3><span id=\"Using_the_osremove_function\">Using the <code>os.remove()<\/code> function<\/span><\/h3>\n<p>If we wish to overwrite file, we can delete it and create a new file. To delete a file, we can use the <code>os.remove()<\/code> function. <\/p>\n<p>We will first check whether a given file exists or not using the <code>os.path.exists()<\/code> function. If the file exists, we remove it using the <code>os.remove()<\/code> function. <\/p>\n<p>After this, we create a new file of the same name and write data to it.<\/p>\n<p>For example,<\/p>\n<pre code = \"python\">\nimport os\nif (os.path.exists(\"myfile.txt\")):\n    os.remove(\"myfile.txt\")\nelse:\n    print(\"File Does Not Exists\")\nf = open(\"myfile.txt\", \"w\")\nf.write('ABC')\nf.close()    \n<\/pre>\n<p>Contents of the file.<\/p>\n<pre>\nABC    \n<\/pre>\n<p>That&#8217;s all about how to overwrite file in Python.<\/p>\n<section class=\"read-more-posts\">\n<div class=\"rm-header\">\n<h2>Further reading:<\/h2>\n<\/div>\n<div class=\"rm-wrap\">\n<div class=\"rm-item\">\n<h5><a href=\"https:\/\/java2blog.com\/read-text-file-line-by-line-python\/\" target=\"_blank\" rel=\"noopener\">Read Text File Line by Line in Python<\/a><\/h5>\n<div class=\"ex\">\n            <a href=\"https:\/\/java2blog.com\/read-text-file-line-by-line-python\/\" target=\"_blank\" rel=\"noopener\">Read more \u2192<\/a>\n        <\/div>\n<\/div>\n<div class=\"rm-item\">\n<h5><a href=\"https:\/\/java2blog.com\/python-read-file-into-string\/\" target=\"_blank\" rel=\"noopener\">Read File to String in Python<\/a><\/h5>\n<div class=\"ex\">\n            <a href=\"https:\/\/java2blog.com\/python-read-file-into-string\/\" target=\"_blank\" rel=\"noopener\">Read more \u2192<\/a>\n        <\/div>\n<\/p><\/div>\n<\/div>\n<\/section>\n","protected":false},"excerpt":{"rendered":"<p>Table of ContentsFile Handling in PythonWays to overwrite file in PythonUsing the w parameter in the open() functionUsing the file.truncate() functionUsing the replace() functionUsing the pathlib moduleUsing the os.remove() function 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 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":18268,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[185],"tags":[],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/18195"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=18195"}],"version-history":[{"count":0,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/18195\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media\/18268"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=18195"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=18195"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=18195"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}