Gre*_*att 121
您可以使用os.listdir()来获取源目录中的文件os.path.isfile()以查看它们是否是常规文件(包括*nix系统上的符号链接)和shutil.copy来进行复制.
以下代码仅将源目录中的常规文件复制到目标目录中(我假设您不希望复制任何子目录).
import os
import shutil
src_files = os.listdir(src)
for file_name in src_files:
full_file_name = os.path.join(src, file_name)
if os.path.isfile(full_file_name):
shutil.copy(full_file_name, dest)
Run Code Online (Sandbox Code Playgroud)
Ste*_*ven 27
如果您不想复制整个树(使用子目录等),请使用或glob.glob("path/to/dir/*.*")获取所有文件名的列表,循环遍历列表并使用shutil.copy复制每个文件.
for filename in glob.glob(os.path.join(source_dir, '*.*')):
shutil.copy(filename, dest_dir)
Run Code Online (Sandbox Code Playgroud)
小智 5
import os
import shutil
os.chdir('C:\\') #Make sure you add your source and destination path below
dir_src = ("C:\\foooo\\")
dir_dst = ("C:\\toooo\\")
for filename in os.listdir(dir_src):
if filename.endswith('.txt'):
shutil.copy( dir_src + filename, dir_dst)
print(filename)
Run Code Online (Sandbox Code Playgroud)
小智 5
def recursive_copy_files(source_path, destination_path, override=False):
"""
Recursive copies files from source to destination directory.
:param source_path: source directory
:param destination_path: destination directory
:param override if True all files will be overridden otherwise skip if file exist
:return: count of copied files
"""
files_count = 0
if not os.path.exists(destination_path):
os.mkdir(destination_path)
items = glob.glob(source_path + '/*')
for item in items:
if os.path.isdir(item):
path = os.path.join(destination_path, item.split('/')[-1])
files_count += recursive_copy_files(source_path=item, destination_path=path, override=override)
else:
file = os.path.join(destination_path, item.split('/')[-1])
if not os.path.exists(file) or override:
shutil.copyfile(item, file)
files_count += 1
return files_count
Run Code Online (Sandbox Code Playgroud)