Python Copying File and Directories

From rbachwiki
Revision as of 17:48, 29 June 2022 by Bacchas (talk | contribs)
Jump to navigation Jump to search

Copying a single file

import shutil

src_path = r"C:/Users/jim/Dropbox/Filing Cabinet/Karaoke Stuff/newsongscode.txt"
dst_path = r"C:/Users/jim/Dropbox/All Folders/websites/msites/rb222/newsongscode.txt"
shutil.copy(src_path, dst_path)
print('copied')

Copy all files from a directory

import os
import shutil

source_folder = r"E:\demos\files\reports\\"
destination_folder = r"E:\demos\files\account\\"

# fetch all files
for file_name in os.listdir(source_folder):
   # construct full file path
   source = source_folder + file_name
   destination = destination_folder + file_name
   # copy only files
   if os.path.isfile(source):
       shutil.copy(source, destination)
       print('copied', file_name)

Copy Entire Directory

import shutil

source_dir = r"E:\demos\files\reports"
destination_dir = r"E:\demos\files\account"
shutil.copytree(source_dir, destination_dir)