用Python选择PC机中的随机目录

2024-10-04 05:23:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python3.x,我不知道如何让我的脚本随机选择同一台电脑中的目录来复制文件。在

我要它复制随机目录中的文件。我该怎么做才能实现呢?在

from sys import argv

import os

import random

script=argv

name=str(script[0])

count = 0

i = 10
while (count < i) :

os.system('start omnomnom.txt')
count+=1

os.mkdir('tembilaland')
os.system(r"copy omnomnom.txt tembilaland")
os.system(r"copy acme.py tembilaland")

Tags: 文件import目录txt脚本oscountscript
2条回答

我不知道你为什么这么做。。。老实说:^)

如果没有预先确定的目标目录列表,可以使用^{}然后^{}来选择一个。在

比如:

# all subdirectories in the user's home
directories = [row[0] for row in os.walk(os.path.expanduser('~/subdir'))]
# or if you want to limit to an arbitrary number
directories = []
for i, row in enumerate(os.walk(os.path.expanduser('~'))):
    if i > 100: break
    directories+= [row[0]]

print random.choice(directories)

如果要在文件夹中查找随机目录,可以使用以下代码:

files = os.listdir("path") //path is the folder path
for f in files:
    if os.path.isdir(f):
       put the directory into an array

最后,从数组中随机选择目录。希望这有帮助。在

相关问题 更多 >