随机指定文件夹中的文件名

时间:2019-05-17 21:04:20

标签: python

我有一个包含文件的特定文件夹,我需要随机化它们的名称。文件夹位置必须能够更改,文件名应包含a-z中的6-10个字符。如何在python中执行此操作?

2 个答案:

答案 0 :(得分:1)

 import string, random
 from random import randint
 import os, sys

 path = raw_input("Location of directory")
 nameDirectory = ''.join(random.choice(string.ascii_lowercase) for _ in xrange(randint(6, 10)))
 pathDir = path + "/" + nameDirectory
 print "name of new directory with path " + pathDir
 os.mkdir( pathDir, 0755 )

还可以在脚本中读取新创建目录的权限。

答案 1 :(得分:1)

我将提供与@ user1929959的优质产品几乎相同的答案。唯一的区别是我的版本在6到10之间变化了字母的数量。因此,在我的版本中产生名称的实际行是:

newname = ''.join([choice(ascii_lowercase) for _ in range(randint(6, 10))])

更新:我意识到也许您想要的东西与其他答案不同...您想重命名现有文件。这是执行此操作的代码,除了只打印重命名操作而不是执行重命名操作,这样我可以看到会发生什么,而不必在测试过程中不断重命名文件。您可以将print()行更改为os.rename()调用以实际进行重命名。

from string import ascii_lowercase
from random import choice, randint, random
import os

def randomize_files(dir):
    for f in os.listdir(dir):
        path = os.path.join(dir, f)
        if os.path.isfile(path):
            newpath = os.path.join(dir, ''.join([choice(ascii_lowercase) for _ in range(randint(5, 8))]))
            # os.rename(path, newpath)
            print("rename {} to {}".format(path, newpath))

randomize_files("/tmp/tset21")

其中包含4个文件的测试目录的结果:

rename /tmp/tset21/bb to /tmp/tset21/idqjp
rename /tmp/tset21/dd to /tmp/tset21/zlyeflfa
rename /tmp/tset21/aa to /tmp/tset21/jjbvrm
rename /tmp/tset21/cc to /tmp/tset21/pkywyyz