Cách sao chép tất cả các tệp có trong một thư mục sang thư mục khác bằng Python. Tôi có đường dẫn nguồn và đường dẫn đích như chuỗi.
Leocrimson
6721 Huy hiệu vàng10 Huy hiệu bạc24 Huy hiệu đồng1 gold badge10 silver badges24 bronze badges
Hỏi ngày 3 tháng 8 năm 2010 lúc 14:54Aug 3, 2010 at 14:54
1
Bạn có thể sử dụng Os.ListDir [] để lấy các tệp trong thư mục nguồn, OS.Path.isFile [] để xem chúng có phải là tệp thông thường không [bao gồm các liên kết tượng trưng trên các hệ thống *NIX] và SOWLIL.COPY để sao chép.
Mã sau chỉ sao chép các tệp thông thường từ thư mục nguồn vào thư mục đích [tôi giả sử bạn không muốn có bất kỳ thư mục phụ nào được sao chép].
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]
K Erlandsson
13.2k6 Huy hiệu vàng50 Huy hiệu bạc66 Huy hiệu đồng6 gold badges50 silver badges66 bronze badges
Đã trả lời ngày 3 tháng 8 năm 2010 lúc 17:59Aug 3, 2010 at 17:59
GreenmattgreenmattGreenMatt
17,9K7 Huy hiệu vàng51 Huy hiệu bạc77 Huy hiệu đồng7 gold badges51 silver badges77 bronze badges
3
Nếu bạn không muốn sao chép toàn bộ cây [với các subdirs, v.v.], hãy sử dụng hoặc glob.glob["path/to/dir/*.*"]
để lấy danh sách tất cả các tên tệp, lặp qua danh sách và sử dụng ____10 để sao chép từng tệp.
for filename in glob.glob[os.path.join[source_dir, '*.*']]:
shutil.copy[filename, dest_dir]
Đã trả lời ngày 3 tháng 8 năm 2010 lúc 15:56Aug 3, 2010 at 15:56
StevenstevenSteven
27.3K5 Huy hiệu vàng60 Huy hiệu bạc 50 Huy hiệu Đồng5 gold badges60 silver badges50 bronze badges
2
Nhìn vào SHOWIL trong các tài liệu Python, cụ thể là lệnh CopyTree.
Nếu thư mục đích đã tồn tại, hãy thử:
shutil.copytree[source, destination, dirs_exist_ok=True]
Codersl
2.2044 huy hiệu vàng28 Huy hiệu bạc32 Huy hiệu đồng4 gold badges28 silver badges32 bronze badges
Đã trả lời ngày 3 tháng 8 năm 2010 lúc 14:57Aug 3, 2010 at 14:57
DoondoonDoon
19.2k3 Huy hiệu vàng38 Huy hiệu bạc44 Huy hiệu đồng3 gold badges38 silver badges44 bronze badges
3
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]
Đã trả lời ngày 23 tháng 8 năm 2016 lúc 0:08Aug 23, 2016 at 0:08
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
Đã trả lời ngày 18 tháng 10 năm 2017 lúc 23:12Oct 18, 2017 at 23:12
3
Dưới đây là một ví dụ khác về chức năng sao chép đệ quy cho phép bạn sao chép nội dung của thư mục [bao gồm cả thư mục con] một tệp tại một thời điểm mà tôi đã sử dụng để giải quyết vấn đề này.
import os
import shutil
def recursive_copy[src, dest]:
"""
Copy each file from src dir to dest dir, including sub-directories.
"""
for item in os.listdir[src]:
file_path = os.path.join[src, item]
# if item is a file, copy it
if os.path.isfile[file_path]:
shutil.copy[file_path, dest]
# else if item is a folder, recurse
elif os.path.isdir[file_path]:
new_dest = os.path.join[dest, item]
os.mkdir[new_dest]
recursive_copy[file_path, new_dest]
Chỉnh sửa: Nếu bạn có thể, chắc chắn chỉ cần sử dụng
1. Điều này đòi hỏi thư mục đích đó chưa tồn tại mặc dù. Nếu bạn cần sao chép các tệp vào một thư mục hiện có, phương thức trên hoạt động tốt! If you can, definitely just use for filename in glob.glob[os.path.join[source_dir, '*.*']]:
shutil.copy[filename, dest_dir]
for filename in glob.glob[os.path.join[source_dir, '*.*']]:
shutil.copy[filename, dest_dir]
1. This requires that that destination folder does not already exist though. If you need to copy files into an existing folder, the above method works well!Đã trả lời ngày 29 tháng 10 năm 2018 lúc 20:10Oct 29, 2018 at 20:10
Dustin Michelsdustin MichelsDustin Michels
2.6312 Huy hiệu vàng18 Huy hiệu bạc28 Huy hiệu đồng2 gold badges18 silver badges28 bronze badges
2
Câu trả lời được xếp hạng hàng đầu sẽ đưa ra lỗi thời gian chạy vì nó cố gắng tham gia một danh sách có tên tệp trên dòng 5, khi nó được cho là tham gia một chuỗi với một chuỗi khác. Tạo một biến khác gọi là PATHSRC và sử dụng nó trong đối số tham gia. Tôi cũng sẽ tạo một biến khác có tên là PathDest và kết hợp nó với File_Name trên dòng cuối cùng. Tôi cũng đã nhập phương thức cần thiết từ SHOTIL chứ không phải toàn bộ mô -đun.
import os
from shutil import copyfile
pathSrc = "the folder where the src files are"
pathDest = "the folder where the dest files are going"
src_files = os.listdir[src]
for file_name in src_files:
full_file_name = os.path.join[pathSrc, file_name]
if os.path.isfile[full_file_name]:
shutil.copy[full_file_name, pathDest + file_name]
Đã trả lời ngày 4 tháng 10 năm 2021 lúc 21:32Oct 4, 2021 at 21:32
Tại sao không phải là một dòng?
import os
import shutil
dest = 'path/to/destination/folder'
src = 'path/to/source/folder/' # mind the '/' at the end
[shutil.copy[src+fn, dest] for fn in os.listdir[src]]
Hoặc với một điều kiện xử lý lỗi
import os
import shutil
dest = 'path/to/destination/folder'
src = 'path/to/source/folder/' # mind the '/' at the end
try:
[shutil.copy[src+fn, dest] for fn in os.listdir[src]]
except:
print['files already exist in', dest]
Đã trả lời ngày 27 tháng 5 lúc 6:12May 27 at 6:12