{"id":18896,"date":"2022-01-15T08:58:49","date_gmt":"2022-01-15T03:28:49","guid":{"rendered":"http:\/\/www.pythonpool.com\/?p=18896"},"modified":"2022-01-15T08:58:52","modified_gmt":"2022-01-15T03:28:52","slug":"python-copy-file","status":"publish","type":"post","link":"https:\/\/www.pythonpool.com\/python-copy-file\/","title":{"rendered":"Easily Copy File Using Python"},"content":{"rendered":"\n<p>In this journey of learning the python programming, let&#8217;s take a step ahead and learn some new concepts. Almost everyone here is pretty aware of file handling operations in python or at least heard of that. But besides that, do you know that python also provides us the programming interface to copy files within your system. So, today in this article, we will discuss <strong>Copying File Using Python Programming<\/strong> <strong>Language. <\/strong>For this, we will use the <strong>Copyfile() method. <\/strong>So, Let&#8217;s get started.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_74 counter-hierarchy ez-toc-counter ez-toc-transparent ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #990303;color:#990303\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #990303;color:#990303\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 eztoc-toggle-hide-by-default' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Copy_file_Using_Shutil_Module_in_Python\" >Copy file Using Shutil Module in Python<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Installation_and_Syntax\" >Installation and Syntax<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Method_1_shutilcopyfile\" >Method 1: shutil.copyfile()<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Example_1_Copying_the_File\" >Example 1: Copying the File<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Method_2_shutilcopy_Method\" >Method 2 : shutil.copy() Method<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Example_2\" >Example 2:<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Method_3_Using_shutilcopy2_method\" >Method 3: Using shutil.copy2() method<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Example_3\" >Example 3:<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Method_4_Using_copyfileobj_method\" >Method 4: Using copyfileobj() method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Errors_while_using_CopyCopy2Copyfile_method\" >Errors while using Copy()\/Copy2()\/Copyfile() method<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Example_4_Same_File_Error\" >Example 4: Same File Error<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Example_5_Python_Copy_File_and_Rename\" >Example 5: Python Copy File and Rename<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Example_6_Permission_Denied_Error\" >Example 6: Permission Denied Error<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Method_5_Python_Copy_File_using_OS_module\" >Method 5: Python Copy File using OS module<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Example_7_Copying_file_using_system_method_of_OS_module\" >Example 7: Copying file using system() method of OS module<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Example_8_Copying_file_using_popen_method_of_OS_module\" >Example 8: Copying file using popen() method of OS module<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Method_6_Python_Copy_file_using_Subprocess_Module\" >Method 6: Python Copy file using Subprocess Module<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#FAQs_on_Python_Copy_File\" >FAQs on Python Copy File<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-19\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Conclusion\" >Conclusion<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-20\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#Trending_Python_Articles\" >Trending Python Articles<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\" id=\"h-copy-file-using-shutil-module-in-python\"><span class=\"ez-toc-section\" id=\"Copy_file_Using_Shutil_Module_in_Python\"><\/span>Copy file Using Shutil Module in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>CopyFile method is defined in the <strong>shutil<\/strong> <strong>module <\/strong>of python, which offers several high levels of operations on files. The module provides the functionality of copying files and removing files using python. However, we will only focus on copying a file<strong>. <\/strong>And for this purpose, we will use different available methods in the shutil module, such as <strong>copyfile() method, copy() method, copy2() method<\/strong>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-installation-and-syntax\"><span class=\"ez-toc-section\" id=\"Installation_and_Syntax\"><\/span>Installation and Syntax<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The<span style=\"text-decoration: underline;\"><a href=\"http:\/\/www.pythonpool.com\/python-shutil\/\" target=\"_blank\" rel=\"noreferrer noopener\"> <strong>shutil module<\/strong><\/a><\/span> is built-in python and didn&#8217;t require any explicit installation. So let&#8217;s go with the syntax.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-method-1-shutil-copyfile\"><span class=\"ez-toc-section\" id=\"Method_1_shutilcopyfile\"><\/span>Method 1: shutil.copyfile()<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>shutil.copyfile(src, dst, *, follow_symlinks=True)<\/code><\/pre>\n\n\n\n<p>Copyfile() methods consist of the following arguments in which the first two is positional argument and the rest after &#8220;*&#8221; is keyword argument which means we have to specify its name.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>src : <\/strong><em>This arguments specifies the source of the file which we want to copy. It contains the complete path of the file and should be passed as first argument.<\/em><\/li><li><strong>dst : <\/strong><em>This is the second argument of the method and specifies the destination of the file and hence requires complete path. <\/em><\/li><li><strong>follow_symlinks : <\/strong><em>This argument specifies that if the source path is a link, then it new link is generated rather than than copying the file. However, its default value is True which will copy the file to destination.<\/em><\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-example-1-copying-the-file\"><span class=\"ez-toc-section\" id=\"Example_1_Copying_the_File\"><\/span>Example 1: Copying the File<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Once you understand the syntax, let&#8217;s see some examples to understand it.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport shutil\nimport os\n\n# Specifying path to source file\nsrc = 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Source\\\\src.txt'\n# Specifying path of destination directory\ndst = 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination\\\\file.txt'\n# Checking all files in Destination folder before copying\nprint(os.listdir('C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination'))\n\nshutil.copyfile(src,dst)\n# Checking all files in Destination folder after copying   \nprint(os.listdir('C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination'))\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;]\n&#91;'file.txt']<\/code><\/pre>\n\n\n\n<p>So, in the above example, we first imported the required library. After that, we have specified the source and destination paths. Then we checked all the available files in the destination folder, which returns an empty list, meaning no file is present there. After that, we called the <strong>copyfile() <\/strong>method to copy the file. Then we again checked the available files present in the destination folder, which returned a list having the file name we specified, which means the file is copied successfully.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-method-2-shutil-copy-method\"><span class=\"ez-toc-section\" id=\"Method_2_shutilcopy_Method\"><\/span>Method 2 : shutil.copy() Method<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>This method is used when we have to copy a file from a source to a destination file or directory. It is slightly different from the above method as it constrains us to specify the file name also in the directory. However, if we specify the destination <a href=\"https:\/\/en.wikipedia.org\/wiki\/Directory\" target=\"_blank\" rel=\"noreferrer noopener\">directory<\/a> only, it will copy the file with the same name in that directory. Let&#8217;s see the example. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-example-2\"><span class=\"ez-toc-section\" id=\"Example_2\"><\/span>Example 2: <span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport shutil\nimport os\n\n# Specifying path to source file\nsrc = 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Source\\\\src.txt'\n# Specifying path of destination directory\ndst = 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination\\\\'\n# Checking all files in Destination folder before copying\nprint(os.listdir('C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination'))\n\nshutil.copy(src,dst)\n# Checking all files in Destination folder after copying   \nprint(os.listdir('C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination'))\n\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;'file.txt']\n&#91;'file.txt', 'src.txt']\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-method-3-using-shutil-copy2-method\"><span class=\"ez-toc-section\" id=\"Method_3_Using_shutilcopy2_method\"><\/span>Method 3: Using shutil.copy2() method<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>So, as in the above case, we are copying the file from source to destination, and it is happening successfully, but the thing to note there is that it does not copy the metadata of the source file and the destination file. Using this method, we can also carry the metadata in the variable and use it in our program. Let&#8217;s see an example to understand that.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-example-3\"><span class=\"ez-toc-section\" id=\"Example_3\"><\/span>Example 3:<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport shutil\nimport os\n\n# Specifying path to source file\nsrc = 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Source\\\\src.txt'\n# Specifying path of destination directory\n\n# checking metadata before copying\nmetadata = os.stat(src) \nprint(&quot;Metadata:&quot;, metadata, &quot;\\n&quot;) \ndst = 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination\\\\'\n# Checking all files in Destination folder before copying\nprint(os.listdir('C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination'))\n\nshutil.copy2(src,dst)\n# Checking all files in Destination folder after copying   \nprint(os.listdir('C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination'))\n# checking metadata after copying\nmetadata = os.stat(dst) \nprint(&quot;Metadata:&quot;, metadata, &quot;\\n&quot;) \n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Metadata: os.stat_result(st_mode=33206, st_ino=3659174697811557, st_dev=754595617, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1641231548, st_mtime=1640758747, st_ctime=1641231548) \n&#91;'file.txt', 'src.txt']\n&#91;'file.txt', 'src.txt']\nMetadata: os.stat_result(st_mode=16895, st_ino=7881299348471393, st_dev=754595617, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1642063317, st_mtime=1642063146, st_ctime=1641231548) <\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-method-4-using-copyfileobj-method\"><span class=\"ez-toc-section\" id=\"Method_4_Using_copyfileobj_method\"><\/span>Method 4: Using copyfileobj() method<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>This is another available method in the shutil module. It also copies a file from the source file to the destination file. In this method, we also need to mention the destination file&#8217;s name in the path to copy the file. However, this method is slightly different. In this method, we first open the source file in the read byte mode, and then we have to open the destination file in write byte mode. Once we are done with opening the file, we use the copyfileobj() to copy the content from the source to the destination. Let&#8217;s see an example.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport shutil\nimport os\n\n# Specifying path to source file and opening it\nsrc = 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Source\\\\src.txt'\nsrc_open = open(src,'rb')\n# Specifying path of destination directory and opening it\ndst = 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination\\\\dst.txt'\ndst_open = open(dst,'wb')\n# Checking all files in Destination folder before copying\nprint(os.listdir('C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination'))\n\nshutil.copyfileobj(src_open,dst_open)\n# Checking all files in Destination folder after copying   \nprint(os.listdir('C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination'))\n\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;'dst.txt', 'file.txt', 'src.txt']<\/code><\/pre>\n\n\n<div class=\"monsterinsights-inline-popular-posts monsterinsights-inline-popular-posts-kilo monsterinsights-popular-posts-styled\" ><div class=\"monsterinsights-inline-popular-posts-text\"><span class=\"monsterinsights-inline-popular-posts-label\" >Popular now<\/span><span class=\"monsterinsights-inline-popular-posts-border\" ><\/span><span class=\"monsterinsights-inline-popular-posts-border-2\" ><\/span><div class=\"monsterinsights-inline-popular-posts-post\"><a class=\"monsterinsights-inline-popular-posts-title\"  href=\"https:\/\/www.pythonpool.com\/fixed-typeerror-cant-compare-datetime-datetime-to-datetime-date\/\">[Fixed] typeerror can&#8217;t compare datetime.datetime to datetime.date<\/a><\/div><\/div><\/div><p><\/p>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-errors-while-using-copy-copy2-copyfile-method\"><span class=\"ez-toc-section\" id=\"Errors_while_using_CopyCopy2Copyfile_method\"><\/span>Errors while using Copy()\/Copy2()\/Copyfile() method<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>However, we encounter different errors while copying the file. Let see some of them.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-example-4-same-file-error\"><span class=\"ez-toc-section\" id=\"Example_4_Same_File_Error\"><\/span>Example 4: Same File Error<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>If we specify the source and destination path the same, it will raise the <strong>Same File Error<\/strong>. However, if we change the file name only, it will copy that.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport shutil\nimport os\n\n# Specifying path to source file\nsrc = 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Source\\\\src.txt'\n# Specifying path of destination directory\ndst = 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Source\\\\src.txt'\n\nshutil.copyfile(src,dst)\n<\/pre><\/div>\n\n\n<p> <strong>Output:<\/strong> <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Traceback (most recent call last):\n  File \"C:\/Users\/Rishav Raj\/OneDrive\/Documents\/PythonPool\/CopyFile Method\/cpy.py\", line 9, in &lt;module&gt;\n    shutil.copyfile(src,dst)\n  File \"C:\\Users\\Rishav Raj\\AppData\\Local\\Programs\\Python\\Python310\\lib\\shutil.py\", line 234, in copyfile\n    raise SameFileError(\"{!r} and {!r} are the same file\".format(src, dst))\nshutil.SameFileError: 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Source\\\\src.txt' and 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Source\\\\src.txt' are the same file\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-example-5-python-copy-file-and-rename\"><span class=\"ez-toc-section\" id=\"Example_5_Python_Copy_File_and_Rename\"><\/span>Example 5: Python Copy File and Rename<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>So, in the above case, we can avoid the error by copying the file with another name or changing the path. In the first example, we have seen how we can specify the directory path in which we want to copy. In this example, we have to make a change, and that is at the end of the path, we should change the file&#8217;s name. We are going to change it from src.txt to <a href=\"http:\/\/www.pythonpool.com\/python-rename-file\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong><span style=\"text-decoration: underline;\">rename<\/span><\/strong><\/a>.txt.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport shutil\nimport os\n\n# Specifying path to source file\nsrc = 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Source\\\\src.txt'\n# Specifying path of source directory and renaming the file\ndst = 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Source\\\\rename.txt'\n\nshutil.copyfile(src,dst)\n\nprint(os.listdir('C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Source'))\n<\/pre><\/div>\n\n\n<p> <strong>Output:<\/strong> <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;'src.txt','rename.txt']<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-example-6-permission-denied-error\"><span class=\"ez-toc-section\" id=\"Example_6_Permission_Denied_Error\"><\/span>Example 6: Permission Denied Error<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>However, if the destination path is a folder, not a file, it raises the permission error. So, we need to specify the complete path of the destination. The previous version raises a Directory error, which meant the same. In another case, if the user doesn&#8217;t;t have permission to copy the files, it raises the same error.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport shutil\nimport os\n\n# Specifying path to source file\nsrc = 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Source\\\\src.txt'\n# Specifying path of destination directory\ndst = 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination'\n# Checking all files in Destination folder before copying\nprint(os.listdir('C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination'))\n\nshutil.copyfile(src,dst)\n# Checking all files in Destination folder after copying   \nprint(os.listdir('C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination'))\n<\/pre><\/div>\n\n\n<p> <strong>Output:<\/strong> <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Traceback (most recent call last):\n  File \"C:\/Users\/Rishav Raj\/OneDrive\/Documents\/PythonPool\/CopyFile Method\/cpy.py\", line 11, in &lt;module&gt;\n    shutil.copyfile(src,dst)\n  File \"C:\\Users\\Rishav Raj\\AppData\\Local\\Programs\\Python\\Python310\\lib\\shutil.py\", line 256, in copyfile\n    with open(dst, 'wb') as fdst:\nPermissionError: &#91;Errno 13] Permission denied: 'C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Destination'<\/code><\/pre>\n\n\n<div class=\"monsterinsights-inline-popular-posts monsterinsights-inline-popular-posts-delta monsterinsights-popular-posts-styled\" ><div class=\"monsterinsights-inline-popular-posts-text\"><span class=\"monsterinsights-inline-popular-posts-icon\" style=\"\"><svg width=\"14\" height=\"19\" viewBox=\"0 0 14 19\" fill=\"none\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\"><path d=\"M7.875 0.899463C7.875 1.59183 8.0816 2.24711 8.49479 2.8653C8.93229 3.48349 9.44271 4.06458 10.026 4.60859C10.6337 5.15259 11.2292 5.73369 11.8125 6.35188C12.4201 6.97007 12.9306 7.76135 13.3438 8.72572C13.7812 9.66537 14 10.7163 14 11.8785C14 13.832 13.3073 15.5011 11.9219 16.8858C10.5608 18.2953 8.92014 19 7 19C5.07986 19 3.42708 18.2953 2.04167 16.8858C0.680556 15.5011 0 13.832 0 11.8785C0 9.94973 0.668403 8.28062 2.00521 6.87116C2.27257 6.57443 2.58854 6.50024 2.95312 6.64861C3.31771 6.79697 3.5 7.08134 3.5 7.50171V10.6545C3.5 11.3221 3.71875 11.8908 4.15625 12.3607C4.61806 12.8305 5.16493 13.0654 5.79688 13.0654C6.45312 13.0654 7.01215 12.8428 7.47396 12.3978C7.93576 11.9279 8.16667 11.3592 8.16667 10.6916C8.16667 10.2712 8.04514 9.86318 7.80208 9.46754C7.58333 9.0719 7.31597 8.71336 7 8.3919C6.68403 8.07044 6.34375 7.73662 5.97917 7.39043C5.63889 7.04425 5.34722 6.66097 5.10417 6.2406C4.88542 5.82024 4.73958 5.35041 4.66667 4.83114C4.59375 4.31186 4.67882 3.68131 4.92188 2.93948C5.18924 2.17293 5.63889 1.33219 6.27083 0.417277C6.51389 0.0463641 6.84201 -0.0772735 7.25521 0.0463641C7.6684 0.170002 7.875 0.454368 7.875 0.899463Z\" fill=\"#EB5757\"><\/path><\/svg><\/span><span class=\"monsterinsights-inline-popular-posts-label\" >Trending<\/span><div class=\"monsterinsights-inline-popular-posts-post\"><a class=\"monsterinsights-inline-popular-posts-title\"  href=\"https:\/\/www.pythonpool.com\/fixed-nameerror-name-unicode-is-not-defined\/\">[Fixed] nameerror: name Unicode is not defined<\/a><\/div><\/div><\/div><p><\/p>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-method-5-python-copy-file-using-os-module\"><span class=\"ez-toc-section\" id=\"Method_5_Python_Copy_File_using_OS_module\"><\/span>Method 5: Python Copy File using OS module<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-example-7-copying-file-using-system-method-of-os-module\"><span class=\"ez-toc-section\" id=\"Example_7_Copying_file_using_system_method_of_OS_module\"><\/span>Example 7: Copying file using system() method of OS module<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Besides using the shutil module, we can also copy the OS module&#8217;s file. There are two available methods for doing that, i.e., <strong>popen() method and system() method. <\/strong>We have to pass the command along with the source file name and destination file in both methods. The &#8220;cp&#8221; command is used for Unix\/Linux users and the copy command for windows users. Let&#8217;s see an example for each.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport os\n\nos.chdir('C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Source')\nprint(os.getcwd())\nos.system('copy src.txt dst2.txt')\n<\/pre><\/div>\n\n\n<p> <strong>Output:<\/strong> <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source\n        1 file(s) copied.<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-example-8-copying-file-using-popen-method-of-os-module\"><span class=\"ez-toc-section\" id=\"Example_8_Copying_file_using_popen_method_of_OS_module\"><\/span>Example 8: Copying file using popen() method of OS module<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport os\n\nos.chdir('C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Source')\nprint(os.getcwd())\nos.popen('copy src.txt dst3.txt')\n<\/pre><\/div>\n\n\n<p> <strong>Output:<\/strong> <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-method-6-python-copy-file-using-subprocess-module\"><span class=\"ez-toc-section\" id=\"Method_6_Python_Copy_file_using_Subprocess_Module\"><\/span>Method 6: Python Copy file using Subprocess Module<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>So, as similar to the OS module, we can also copy the file using the SUbprocess module. We will use the call() method inside the module. The syntax is similar to the system function. Let&#8217;s see the example.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport subprocess,os\n\nos.chdir('C:\\\\Users\\\\Rishav Raj\\\\OneDrive\\\\Documents\\\\PythonPool\\\\CopyFile Method\\\\Source')\nprint(os.getcwd())\nstatus = subprocess.call('copy src.txt dst4.txt', shell=True)\n<\/pre><\/div>\n\n\n<p> <strong>Output:<\/strong> <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source\n        1 file(s) copied.<\/code><\/pre>\n\n\n<div class=\"monsterinsights-inline-popular-posts monsterinsights-inline-popular-posts-beta monsterinsights-popular-posts-styled\" ><div class=\"monsterinsights-inline-popular-posts-image\"><a href=\"https:\/\/www.pythonpool.com\/solved-runtimeerror-cuda-error-invalid-device-ordinal\/\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal.webp 1200w \" alt=\"[Solved] runtimeerror: cuda error: invalid device ordinal\" \/><\/a><\/div><div class=\"monsterinsights-inline-popular-posts-text\"><span class=\"monsterinsights-inline-popular-posts-label\" >Trending<\/span><div class=\"monsterinsights-inline-popular-posts-post\"><a class=\"monsterinsights-inline-popular-posts-title\"  href=\"https:\/\/www.pythonpool.com\/solved-runtimeerror-cuda-error-invalid-device-ordinal\/\">[Solved] runtimeerror: cuda error: invalid device ordinal<\/a><\/div><\/div><\/div><p><\/p>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-faqs-on-python-copy-file\"><span class=\"ez-toc-section\" id=\"FAQs_on_Python_Copy_File\"><\/span>FAQs on Python Copy File<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<div class=\"schema-faq wp-block-yoast-faq-block\"><div class=\"schema-faq-section\" id=\"faq-question-1642155208470\"><strong class=\"schema-faq-question\">Q1) How to make a python file copy itself then execute the other copy once?<\/strong> <p class=\"schema-faq-answer\">You can use the following block of code to do that.<br\/><br\/><code>import shutil<\/code><br\/><code>import subprocess <\/code><br\/><code>import os <\/code><br\/><code>import random <\/code><br\/><code>print(\"hello world\") <\/code><br\/><code>new_file_name = str(random.randint(1, 10000)) + \".py\" shutil.copy(__file__, new_file_name) subprocess.call((new_file_name), shell=True)<\/code><\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1642155329964\"><strong class=\"schema-faq-question\">Q2) How to use ansible to copy files without the modern python version?<\/strong> <p class=\"schema-faq-answer\">You can do it in the following way.<br\/><br\/><code>---<\/code><br\/><code> - hosts: M<\/code><br\/><code> tasks:<\/code><br\/>      <code> - name: generate key pair<\/code><br\/>          <code> shell: ssh-keygen -b 2048 -t rsa -f \/root\/.ssh\/id_rsa -q -N \/dev\/null <\/code><br\/>             <code>args: creates: \/root\/.ssh\/id_rsa <\/code><br\/><br\/>       <code>- name: test public key <\/code><br\/>           <code>shell: ssh-keygen -l -f \/root\/.ssh\/id_rsa.pub <\/code><br\/>           <code>changed_when: false <\/code><br\/><br\/>      <code>- name: retrieve public key <\/code><br\/>          <code>shell: cat \/root\/.ssh\/id_rsa.pub <\/code><br\/>          <code>register: master_public_key <\/code><br\/>          <code>changed_when: false <\/code><br\/><code>- hosts: SLAVES<\/code> <br\/>     <code>tasks: <\/code><br\/>        <code>- name: add master public key to slaves <\/code><br\/>            <code>authorized_key: <\/code><br\/>                    <code>user: root <\/code><br\/>                    <code>key: \"{{ hostvars['M'].master_public_key.stdout }}\"<\/code><\/p> <\/div> <\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-conclusion\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>So, today in this article, we learned about copying files in python. For that, we have seen different methods in the shutil module. Besides that, we have also seen OS module and Subprocess module methods for copying the file. We have also seen various examples to understand it more clearly. <\/p>\n\n\n\n<p>After that, we looked at some possible errors while copying the file. We should avoid ourselves to be in any such situation that raises the error and have to be more careful while handling the directories to copy the files. I hope this article has helped you. Thank You.<\/p>\n\n\n<div class=\"monsterinsights-widget-popular-posts monsterinsights-widget-popular-posts-delta monsterinsights-popular-posts-styled monsterinsights-widget-popular-posts-columns-2\"><h2 class=\"monsterinsights-widget-popular-posts-widget-title\"><span class=\"ez-toc-section\" id=\"Trending_Python_Articles\"><\/span>Trending Python Articles<span class=\"ez-toc-section-end\"><\/span><\/h2><ul class=\"monsterinsights-widget-popular-posts-list\"><li ><a href=\"https:\/\/www.pythonpool.com\/fixed-typeerror-cant-compare-datetime-datetime-to-datetime-date\/\"><div class=\"monsterinsights-widget-popular-posts-image\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_.webp 1200w \" alt=\"[Fixed] typeerror can&#8217;t compare datetime.datetime to datetime.date\" \/><\/div><div class=\"monsterinsights-widget-popular-posts-text\"><span class=\"monsterinsights-widget-popular-posts-title\" >[Fixed] typeerror can&#8217;t compare datetime.datetime to datetime.date<\/span><div class=\"monsterinsights-widget-popular-posts-meta\" ><span class=\"monsterinsights-widget-popular-posts-author\">by Namrata Gulati<\/span><span>&#9679;<\/span><span class=\"monsterinsights-widget-popular-posts-date\">January 11, 2024<\/span><\/div><\/div><\/a><\/li><li ><a href=\"https:\/\/www.pythonpool.com\/fixed-nameerror-name-unicode-is-not-defined\/\"><div class=\"monsterinsights-widget-popular-posts-image\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined.webp 1200w \" alt=\"[Fixed] nameerror: name Unicode is not defined\" \/><\/div><div class=\"monsterinsights-widget-popular-posts-text\"><span class=\"monsterinsights-widget-popular-posts-title\" >[Fixed] nameerror: name Unicode is not defined<\/span><div class=\"monsterinsights-widget-popular-posts-meta\" ><span class=\"monsterinsights-widget-popular-posts-author\">by Namrata Gulati<\/span><span>&#9679;<\/span><span class=\"monsterinsights-widget-popular-posts-date\">January 2, 2024<\/span><\/div><\/div><\/a><\/li><li ><a href=\"https:\/\/www.pythonpool.com\/solved-runtimeerror-cuda-error-invalid-device-ordinal\/\"><div class=\"monsterinsights-widget-popular-posts-image\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal.webp 1200w \" alt=\"[Solved] runtimeerror: cuda error: invalid device ordinal\" \/><\/div><div class=\"monsterinsights-widget-popular-posts-text\"><span class=\"monsterinsights-widget-popular-posts-title\" >[Solved] runtimeerror: cuda error: invalid device ordinal<\/span><div class=\"monsterinsights-widget-popular-posts-meta\" ><span class=\"monsterinsights-widget-popular-posts-author\">by Namrata Gulati<\/span><span>&#9679;<\/span><span class=\"monsterinsights-widget-popular-posts-date\">January 2, 2024<\/span><\/div><\/div><\/a><\/li><li ><a href=\"https:\/\/www.pythonpool.com\/fixed-typeerror-type-numpy-ndarray-doesnt-define-__round__-method\/\"><div class=\"monsterinsights-widget-popular-posts-image\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method.webp 1200w \" alt=\"[Fixed] typeerror: type numpy.ndarray doesn&#8217;t define __round__ method\" \/><\/div><div class=\"monsterinsights-widget-popular-posts-text\"><span class=\"monsterinsights-widget-popular-posts-title\" >[Fixed] typeerror: type numpy.ndarray doesn&#8217;t define __round__ method<\/span><div class=\"monsterinsights-widget-popular-posts-meta\" ><span class=\"monsterinsights-widget-popular-posts-author\">by Namrata Gulati<\/span><span>&#9679;<\/span><span class=\"monsterinsights-widget-popular-posts-date\">January 2, 2024<\/span><\/div><\/div><\/a><\/li><\/ul><\/div><p><\/p>","protected":false},"excerpt":{"rendered":"<p>In this journey of learning the python programming, let&#8217;s take a step ahead and learn some new concepts. Almost everyone here is pretty aware of &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Easily Copy File Using Python\" class=\"read-more button\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/#more-18896\" aria-label=\"More on Easily Copy File Using Python\">Read more<\/a><\/p>\n","protected":false},"author":25,"featured_media":19127,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_mi_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[15],"tags":[4667,1294,4672,4669,4674,4673,4676,1281,1280,4666,4671,4675,4670,4668,3680,3684],"class_list":["post-18896","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tutorials","tag-copy-a-file-in-python","tag-copy-and-rename-file-python","tag-how-to-copy-a-file-in-python","tag-os-copy-file-python","tag-python-3-copy-file","tag-python-copy-a-file","tag-python-copy-and-paste-file","tag-python-copy-and-rename-file","tag-python-copy-file-and-rename","tag-python-copy-file-to-another-directory","tag-python-copy-file-to-directory","tag-python-copy-paste-file","tag-python-os-copy-file","tag-python-os-copy-file-and-rename","tag-python-shutil-copy","tag-shutil-copy-python","infinite-scroll-item"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v20.1 (Yoast SEO v25.0) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Easily Copy File Using Python - Python Pool<\/title>\n<meta name=\"description\" content=\"In tis article we will learn that how can we copy file in python. For that we will see copyfile() method in python and will see its usage.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.pythonpool.com\/python-copy-file\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Easily Copy File Using Python\" \/>\n<meta property=\"og:description\" content=\"In this journey of learning the python programming, let&#039;s take a step ahead and learn some new concepts. Almost everyone here is pretty aware of file\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pythonpool.com\/python-copy-file\/\" \/>\n<meta property=\"og:site_name\" content=\"Python Pool\" \/>\n<meta property=\"article:published_time\" content=\"2022-01-15T03:28:49+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-01-15T03:28:52+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-copy-file.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"Rishav Raj\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@pythonpool\" \/>\n<meta name=\"twitter:site\" content=\"@pythonpool\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Rishav Raj\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.pythonpool.com\/python-copy-file\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-copy-file\/\"},\"author\":{\"name\":\"Rishav Raj\",\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/person\/025222e28182ecbb97e17f9f1bf15ac4\"},\"headline\":\"Easily Copy File Using Python\",\"datePublished\":\"2022-01-15T03:28:49+00:00\",\"dateModified\":\"2022-01-15T03:28:52+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-copy-file\/\"},\"wordCount\":1143,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.pythonpool.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-copy-file\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-copy-file.webp\",\"keywords\":[\"copy a file in python\",\"copy and rename file python\",\"how to copy a file in python\",\"os copy file python\",\"python 3 copy file\",\"python copy a file\",\"python copy and paste file\",\"python copy and rename file\",\"python copy file and rename\",\"python copy file to another directory\",\"python copy file to directory\",\"python copy paste file\",\"python os copy file\",\"python os copy file and rename\",\"python shutil copy\",\"shutil copy python\"],\"articleSection\":[\"Tutorials\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.pythonpool.com\/python-copy-file\/#respond\"]}]},{\"@type\":[\"WebPage\",\"FAQPage\"],\"@id\":\"https:\/\/www.pythonpool.com\/python-copy-file\/\",\"url\":\"https:\/\/www.pythonpool.com\/python-copy-file\/\",\"name\":\"Easily Copy File Using Python - Python Pool\",\"isPartOf\":{\"@id\":\"https:\/\/www.pythonpool.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-copy-file\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-copy-file\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-copy-file.webp\",\"datePublished\":\"2022-01-15T03:28:49+00:00\",\"dateModified\":\"2022-01-15T03:28:52+00:00\",\"description\":\"In tis article we will learn that how can we copy file in python. For that we will see copyfile() method in python and will see its usage.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-copy-file\/#breadcrumb\"},\"mainEntity\":[{\"@id\":\"https:\/\/www.pythonpool.com\/python-copy-file\/#faq-question-1642155208470\"},{\"@id\":\"https:\/\/www.pythonpool.com\/python-copy-file\/#faq-question-1642155329964\"}],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.pythonpool.com\/python-copy-file\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.pythonpool.com\/python-copy-file\/#primaryimage\",\"url\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-copy-file.webp\",\"contentUrl\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-copy-file.webp\",\"width\":1200,\"height\":628,\"caption\":\"python copy file\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.pythonpool.com\/python-copy-file\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.pythonpool.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Easily Copy File Using Python\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.pythonpool.com\/#website\",\"url\":\"https:\/\/www.pythonpool.com\/\",\"name\":\"Python Pool\",\"description\":\"Your One-Stop Python Learning Destination\",\"publisher\":{\"@id\":\"https:\/\/www.pythonpool.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.pythonpool.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.pythonpool.com\/#organization\",\"name\":\"Python Pool\",\"url\":\"https:\/\/www.pythonpool.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/\",\"url\":\"http:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png\",\"contentUrl\":\"http:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png\",\"width\":452,\"height\":185,\"caption\":\"Python Pool\"},\"image\":{\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/pythonpool\",\"https:\/\/www.youtube.com\/c\/pythonpool\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/person\/025222e28182ecbb97e17f9f1bf15ac4\",\"name\":\"Rishav Raj\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/77d441cf39fc8183322bfc1dcaf04be5c1fd429574820606cccac81fd8e8749a?s=96&d=wavatar&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/77d441cf39fc8183322bfc1dcaf04be5c1fd429574820606cccac81fd8e8749a?s=96&d=wavatar&r=g\",\"caption\":\"Rishav Raj\"}},{\"@type\":\"Question\",\"@id\":\"https:\/\/www.pythonpool.com\/python-copy-file\/#faq-question-1642155208470\",\"position\":1,\"url\":\"https:\/\/www.pythonpool.com\/python-copy-file\/#faq-question-1642155208470\",\"name\":\"Q1) How to make a python file copy itself then execute the other copy once?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"You can use the following block of code to do that.<br \/><br \/>import shutil<br \/>import subprocess <br \/>import os <br \/>import random <br \/>print(\\\"hello world\\\") <br \/>new_file_name = str(random.randint(1, 10000)) + \\\".py\\\" shutil.copy(__file__, new_file_name) subprocess.call((new_file_name), shell=True)\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\/\/www.pythonpool.com\/python-copy-file\/#faq-question-1642155329964\",\"position\":2,\"url\":\"https:\/\/www.pythonpool.com\/python-copy-file\/#faq-question-1642155329964\",\"name\":\"Q2) How to use ansible to copy files without the modern python version?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"You can do it in the following way.<br\/><br\/>---<br\/> - hosts: M<br\/> tasks:<br\/>       - name: generate key pair<br\/>           shell: ssh-keygen -b 2048 -t rsa -f \/root\/.ssh\/id_rsa -q -N \/dev\/null <br\/>             args: creates: \/root\/.ssh\/id_rsa <br\/><br\/>       - name: test public key <br\/>           shell: ssh-keygen -l -f \/root\/.ssh\/id_rsa.pub <br\/>           changed_when: false <br\/><br\/>      - name: retrieve public key <br\/>          shell: cat \/root\/.ssh\/id_rsa.pub <br\/>          register: master_public_key <br\/>          changed_when: false <br\/>- hosts: SLAVES <br\/>     tasks: <br\/>        - name: add master public key to slaves <br\/>            authorized_key: <br\/>                    user: root <br\/>                    key: \\\"{{ hostvars['M'].master_public_key.stdout }}\\\"\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Easily Copy File Using Python - Python Pool","description":"In tis article we will learn that how can we copy file in python. For that we will see copyfile() method in python and will see its usage.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.pythonpool.com\/python-copy-file\/","og_locale":"en_US","og_type":"article","og_title":"Easily Copy File Using Python","og_description":"In this journey of learning the python programming, let's take a step ahead and learn some new concepts. Almost everyone here is pretty aware of file","og_url":"https:\/\/www.pythonpool.com\/python-copy-file\/","og_site_name":"Python Pool","article_published_time":"2022-01-15T03:28:49+00:00","article_modified_time":"2022-01-15T03:28:52+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-copy-file.webp","type":"image\/webp"}],"author":"Rishav Raj","twitter_card":"summary_large_image","twitter_creator":"@pythonpool","twitter_site":"@pythonpool","twitter_misc":{"Written by":"Rishav Raj","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.pythonpool.com\/python-copy-file\/#article","isPartOf":{"@id":"https:\/\/www.pythonpool.com\/python-copy-file\/"},"author":{"name":"Rishav Raj","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/025222e28182ecbb97e17f9f1bf15ac4"},"headline":"Easily Copy File Using Python","datePublished":"2022-01-15T03:28:49+00:00","dateModified":"2022-01-15T03:28:52+00:00","mainEntityOfPage":{"@id":"https:\/\/www.pythonpool.com\/python-copy-file\/"},"wordCount":1143,"commentCount":0,"publisher":{"@id":"https:\/\/www.pythonpool.com\/#organization"},"image":{"@id":"https:\/\/www.pythonpool.com\/python-copy-file\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-copy-file.webp","keywords":["copy a file in python","copy and rename file python","how to copy a file in python","os copy file python","python 3 copy file","python copy a file","python copy and paste file","python copy and rename file","python copy file and rename","python copy file to another directory","python copy file to directory","python copy paste file","python os copy file","python os copy file and rename","python shutil copy","shutil copy python"],"articleSection":["Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.pythonpool.com\/python-copy-file\/#respond"]}]},{"@type":["WebPage","FAQPage"],"@id":"https:\/\/www.pythonpool.com\/python-copy-file\/","url":"https:\/\/www.pythonpool.com\/python-copy-file\/","name":"Easily Copy File Using Python - Python Pool","isPartOf":{"@id":"https:\/\/www.pythonpool.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.pythonpool.com\/python-copy-file\/#primaryimage"},"image":{"@id":"https:\/\/www.pythonpool.com\/python-copy-file\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-copy-file.webp","datePublished":"2022-01-15T03:28:49+00:00","dateModified":"2022-01-15T03:28:52+00:00","description":"In tis article we will learn that how can we copy file in python. For that we will see copyfile() method in python and will see its usage.","breadcrumb":{"@id":"https:\/\/www.pythonpool.com\/python-copy-file\/#breadcrumb"},"mainEntity":[{"@id":"https:\/\/www.pythonpool.com\/python-copy-file\/#faq-question-1642155208470"},{"@id":"https:\/\/www.pythonpool.com\/python-copy-file\/#faq-question-1642155329964"}],"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pythonpool.com\/python-copy-file\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/python-copy-file\/#primaryimage","url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-copy-file.webp","contentUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-copy-file.webp","width":1200,"height":628,"caption":"python copy file"},{"@type":"BreadcrumbList","@id":"https:\/\/www.pythonpool.com\/python-copy-file\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.pythonpool.com\/"},{"@type":"ListItem","position":2,"name":"Easily Copy File Using Python"}]},{"@type":"WebSite","@id":"https:\/\/www.pythonpool.com\/#website","url":"https:\/\/www.pythonpool.com\/","name":"Python Pool","description":"Your One-Stop Python Learning Destination","publisher":{"@id":"https:\/\/www.pythonpool.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.pythonpool.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.pythonpool.com\/#organization","name":"Python Pool","url":"https:\/\/www.pythonpool.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/","url":"http:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png","contentUrl":"http:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png","width":452,"height":185,"caption":"Python Pool"},"image":{"@id":"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/pythonpool","https:\/\/www.youtube.com\/c\/pythonpool"]},{"@type":"Person","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/025222e28182ecbb97e17f9f1bf15ac4","name":"Rishav Raj","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/77d441cf39fc8183322bfc1dcaf04be5c1fd429574820606cccac81fd8e8749a?s=96&d=wavatar&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/77d441cf39fc8183322bfc1dcaf04be5c1fd429574820606cccac81fd8e8749a?s=96&d=wavatar&r=g","caption":"Rishav Raj"}},{"@type":"Question","@id":"https:\/\/www.pythonpool.com\/python-copy-file\/#faq-question-1642155208470","position":1,"url":"https:\/\/www.pythonpool.com\/python-copy-file\/#faq-question-1642155208470","name":"Q1) How to make a python file copy itself then execute the other copy once?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"You can use the following block of code to do that.<br \/><br \/>import shutil<br \/>import subprocess <br \/>import os <br \/>import random <br \/>print(\"hello world\") <br \/>new_file_name = str(random.randint(1, 10000)) + \".py\" shutil.copy(__file__, new_file_name) subprocess.call((new_file_name), shell=True)","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.pythonpool.com\/python-copy-file\/#faq-question-1642155329964","position":2,"url":"https:\/\/www.pythonpool.com\/python-copy-file\/#faq-question-1642155329964","name":"Q2) How to use ansible to copy files without the modern python version?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"You can do it in the following way.<br\/><br\/>---<br\/> - hosts: M<br\/> tasks:<br\/>       - name: generate key pair<br\/>           shell: ssh-keygen -b 2048 -t rsa -f \/root\/.ssh\/id_rsa -q -N \/dev\/null <br\/>             args: creates: \/root\/.ssh\/id_rsa <br\/><br\/>       - name: test public key <br\/>           shell: ssh-keygen -l -f \/root\/.ssh\/id_rsa.pub <br\/>           changed_when: false <br\/><br\/>      - name: retrieve public key <br\/>          shell: cat \/root\/.ssh\/id_rsa.pub <br\/>          register: master_public_key <br\/>          changed_when: false <br\/>- hosts: SLAVES <br\/>     tasks: <br\/>        - name: add master public key to slaves <br\/>            authorized_key: <br\/>                    user: root <br\/>                    key: \"{{ hostvars['M'].master_public_key.stdout }}\"","inLanguage":"en-US"},"inLanguage":"en-US"}]}},"_links":{"self":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/18896","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/users\/25"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/comments?post=18896"}],"version-history":[{"count":24,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/18896\/revisions"}],"predecessor-version":[{"id":19135,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/18896\/revisions\/19135"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/media\/19127"}],"wp:attachment":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/media?parent=18896"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/categories?post=18896"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/tags?post=18896"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}