从文件树中复制随机文件

LM_*_*M_O 6 python random file-io

我和这里有同样的问题,但现在我试图用 python 做同样的事情,因为它更适合这项任务。

我从这个开始:

import os
import shutil
import random
import glob


root_dir = '/home/leonardo/Desktop/python_script/rfe'
output_dir = '/home/leonardo/Desktop/python_script/output_folder'
ref = 200

folders_root_dir = os.listdir(root_dir)
print folders_root_dir

count = len(folders_root_dir)
print  count

for i in xrange(count):
    folder_inside = root_dir + '/' + folders_root_dir[i]
    print folder_inside
    number_files_folder_inside = len(os.listdir(folder_inside))
    print  number_files_folder_inside

    if number_files_folder_inside > ref:
        ref_copy = round(0.2*number_files_folder_inside)
        print ref_copy
        # here I have to copy 20% of the files in this folder to the output folder 
    else:
        # here I have to copy all files from the folder to the output_dir
Run Code Online (Sandbox Code Playgroud)

我尝试使用,os.walk()但我是 python 的新手,并且在函数运行时选择文件被证明是非常困难的。

use*_*863 0

也许类似(未经测试)

    import os
    THRESHOLD = 200
    root_dir = "\home..."
    output_dir = "\home....."

    for top, dirs, nondirs in os.walk(root_dir):
        for name in nondirs[:THRESHOLD]:
            path = os.path.join(top, name)
            destination = os.path.join(output_dir, name)
            os.rename(path, destination)
Run Code Online (Sandbox Code Playgroud)