多次选择和复制随机文件

时间:2012-03-06 16:56:48

标签: python python-3.x

[编辑:见下面的最终代码]我有以下代码,我试图弄清楚在哪里插入random.choice代码,使其选择一个文件,复制它,并重复(这里6次)。

import os
import shutil
import random

dir_input = str(input("Enter Source Directory: "))
src_files = (os.listdir(dir_input))

for x in range (0,5):
    print ('This is the %d time' % x)
    for file_name in src_files:
        full_file_name = (os.path.join(dir_input, file_name))
        if (os.path.isfile(full_file_name)):
        print ('copying...' + full_file_name)
            shutil.copy(full_file_name, r'C:\Dir'))
else:
    print ('Finished!')

4 个答案:

答案 0 :(得分:3)

感谢大家的帮助。当我学到一些东西时,代码发生了重大变化(并得到了本论坛上人们的帮助)。这个网站上的人非常棒。这是代码:

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!')

答案 1 :(得分:1)

您的代码会将每个循环中的所有文件从一个目录复制到'C:\Dir'。这似乎不是你想要的。另外,你说了一个文件。您的代码只会转储输入目录中的所有内容列表。您可能还想考虑使用raw_input而不是输入。这是我的建议:

import os
import shutil
import random

# let's seed the random number, it's at least good practice :-)
random.seed()
dir_input = raw_input("Enter Source Directory: ")
# let's get ONLY the files in this directory
src_files = [ f for f in os.listdir(dir_input) if os.path.isfile(os.path.join(dir_input,f))]
for x in range (0,5):
  print ('This is the %d time' % x)
  # I'll let you copy this where you want, but this will
  # choose a random file once per loop
  print random.choice(src_files)

如果我误解,请告诉我。

答案 2 :(得分:1)

首先过滤路径,以便获得仅包含有效选项的列表:

def valid_path(dir_path, filename):
    full_path = os.path.join(dir_path, filename)
    return os.path.isfile(full_path)

files = [f for f in src_files if valid_path(dir_input, f)]

然后,如果您想要n个唯一文件,可以使用random.sample():

choices = random.sample(files, n)

或者如果您想要允许同一文件的多个实例:

choices = [random.choice(files) for i in range(n)]

答案 3 :(得分:0)

弃用最后一个声明,否则你会在复制过程中看到该信息5次,而不是在复制之后。