Difference between revisions of "Python Copying File and Directories"
Jump to navigation
Jump to search
Line 1: | Line 1: | ||
= Rename Files: example1= | = Rename Files: example1= | ||
< | <pre> | ||
from datetime import datetime | from datetime import datetime | ||
from pathlib import Path | from pathlib import Path | ||
Line 26: | Line 26: | ||
# print(new_name) | # print(new_name) | ||
print(new_path) | print(new_path) | ||
</ | </pre> | ||
= Copying a single file= | = Copying a single file= |
Revision as of 20:44, 15 September 2022
Rename Files: example1
from datetime import datetime from pathlib import Path import os ## This script will rename files and move them into another folder our_files = Path("C:\\Users\\bacchas\Desktop\youtubedl\\test") for file in our_files.iterdir(): if file.suffix != '.cdg' and file.is_file: #make sure its a file and not a directory directory = file.parent extension = file.suffix old_name = file.stem artist, title = old_name.split('-') artist = artist[4:].lstrip() new_name = f'{artist}-{title}{extension}' newpath_name = 'kmp3files' # will create a new path new_path = our_files.joinpath(newpath_name) if not new_path.exists(): new_path.mkdir() new_file_path = new_path.joinpath(new_name) file.rename(new_file_path) # print(new_name) print(new_path)
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)