[英]Trying to copy files with a specific extension from source folder to destination folder
I am testing an idea to copy all files with the extension '.yaml' from one folder (and all sub-folders) to another folder.我正在测试将所有扩展名为“.yaml”的文件从一个文件夹(和所有子文件夹)复制到另一个文件夹的想法。 I came up with the code below.
我想出了下面的代码。
import os
import shutil
src = 'C:\\Users\\ryans\\OneDrive\\Documents\\GitHub\\Pipeline\\'
dest = 'C:\\Users\\ryans\\OneDrive\\Desktop\\AllYAML\\'
#src_files = os.listdir(src)
for root, dirs, files in os.walk(src):
for filename in files:
full_file_name = os.path.join(src, filename)
if (os.path.isfile(full_file_name)):
if full_file_name.endswith('.yaml'):
shutil.copy(full_file_name, dest)
This seems right, for the most part, but it is only copying over two files with the extension '.yaml' from source to destination.这在大多数情况下似乎是正确的,但它只是将扩展名为“.yaml”的两个文件从源复制到目标。 There are around 130 files in all folders and sub-folders, so I know something is off here, but I don't know quite what the issue is.
所有文件夹和子文件夹中大约有 130 个文件,所以我知道这里出了点问题,但我不太清楚问题是什么。
You should join the path of the file with the file name instead of joining the starting path with the file name.您应该将文件路径与文件名连接起来,而不是将起始路径与文件名连接起来。
Change:改变:
full_file_name = os.path.join(src, filename)
to:到:
full_file_name = os.path.join(root, filename)
this should copy all the .yaml files from src folder and its sub-folders into dest folder, keeping in mind the src sub-folder structure will NOT BE maintained in dest.这应该将 src 文件夹及其子文件夹中的所有 .yaml 文件复制到 dest 文件夹中,记住 src 子文件夹结构不会在 dest 中维护。
import os
import shutil
src = 'C:\\Users\\ryans\\OneDrive\\Documents\\GitHub\\Pipeline\\'
dest = 'C:\\Users\\ryans\\OneDrive\\Desktop\\AllYAML\\'
#src_files = os.listdir(src)
for root, dirs, files in os.walk(src):
for filename in files:
full_file_name = os.path.join(root, filename)
if (os.path.isfile(full_file_name)):
if full_file_name.endswith('.yaml'):
shutil.copy(full_file_name, dest)
Mainly filename is to be joined with respective directory to which it belongs like full_file_name = os.path.join(root, filename)主要是文件名要与它所属的各个目录连接,如 full_file_name = os.path.join(root, filename)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.