Python Copy File

The code below shows how to copy and rename file in Python programming language.  A copy of textfile.txt will created and appended a .bak extension. The file will then be renamed using Python os path.

#
# Python Copy File
#
import os
from os import path
import shutil

def main():
  # make a duplicate of an existing file
  if path.exists("textfile.txt"):
    # get the path to the file in the current directory
    src = path.realpath("textfile.txt")
    
    # let's make a backup copy by appending "bak" to the name
    dst = src + ".bak"
    
    # copy over the permissions, modification times, and other info
    shutil.copy(src, dst)
    shutil.copystat(src, dst)

    # rename the original file
    os.rename("textfile.txt", "newfile.txt")
    

if __name__ == "__main__":
  main()



Comments

Popular posts from this blog

How to write to a file in Kotlin

Python Tkinter example