Python3:在目录树中多次选择和复制随机文件

时间:2019-03-29 08:52:34

标签: python-3.x

我对从目录树中复制随机文件感兴趣。我尝试了下面的示例,它对于文件的1个目录非常有效,但是我希望它搜索多个子目录并执行相同的操作。

示例: Selecting and Copying a Random File Several Times

我试图确定如何使用os.walk或shutil.copytree,但不确定该怎么做。预先感谢!

import os
import shutil
import random
import os.path

src_dir = 'C:\\'
target_dir = 'C:\\TEST'
src_files = (os.listdir(src_dir))
def valid_path(dir_path, filename):
    full_path = os.path.join(dir_path, filename)
    return os.path.isfile(full_path)  
files = [os.path.join(src_dir, f) for f in src_files if valid_path(src_dir, f)]
choices = random.sample(files, 5)
for files in choices:
    shutil.copy(files, target_dir)
print ('Finished!')

我已对此进行了更新,但是我注意到os.walk仅给了我树中的最后一个目录,该目录具有5个文件,而不是根目录中的15个文件。不知道我在哪里错了:

import os
import shutil
import random

source_dir = "C:\\test\\from"
target_dir = "C:\\test\\to"  

for path, dirs, filenames in os.walk(source_dir):
    source_files = filenames
    print(source_files) # this gives me 15 files whih is correct

print(source_files) # this gives me only 5 files which is only the last directory

choices = random.sample(source_files, 5)
print(choices)


for files in choices:
    shutil.copy(files, target_dir)

2 个答案:

答案 0 :(得分:0)

您可以尝试使用递归方法: 在这里您可以找到答案。

https://stackoverflow.com/questions/2212643/python-recursive-folder-read/55193831#55193831

答案 1 :(得分:0)

非常感谢您提供的信息,我现在有一个正在运行的程序,可以从计算机中收集随机的mp3,并将其放在手机上。对于那些感兴趣的人,代码如下:

import os
import shutil
import random

# source directory for files to copy from
source_dir = "E:\\_Temp\\Music"
# target directory for files to copy to
target_dir = "C:\\test\\to"  

 # empty list for collecting files
source_files = []  

# walk through directory tree and find files only
for dirpath, dirnames, filenames in os.walk(source_dir):
    for file in filenames:
        if file.endswith(".mp3"):
            source_files.append(os.path.join(dirpath, file))

# select 300 files randomly               
choices = random.sample(source_files, 300)
print(choices)

# copy files to target directory
for files in choices:
    shutil.copy(files, target_dir)
相关问题