简体   繁体   English

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

[英]Randomize file names in a specified folder

I have a specific folder which contains files and I need to randomize their names. 我有一个包含文件的特定文件夹,我需要随机化它们的名称。 Folder location needs to be able to be changeable and file names should contain 6 - 10 characters from a - z. 文件夹位置必须能够更改,文件名应包含a-z中的6-10个字符。 How can I do this in python? 如何在python中做到这一点?

 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 )

Also in script you can read the permission for new created directory. 另外,在脚本中,您可以读取新创建目录的权限。

I was going to offer up pretty much the same answer as @user1929959's fine offering. 我将提供与@ user1929959的优质产品几乎相同的答案。 The only difference is that my version varied the number of letters between 6 and 10. So the actual line that produced the names in my version was: 唯一的区别是我的版本在6到10之间变化了字母的数量。因此,在我的版本中产生名称的实际行是:

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

UPDATE: I realize that maybe you wanted something different than the other answer...you wanted existing files renamed. 更新:我意识到也许您想要的东西不同于其他答案...您想要重命名现有文件。 Here's the code that does that, except that I just print the rename operation rather than doing it so I can see what would happen without having to keep renaming back the files during testing. 这是执行此操作的代码,除了只打印重命名操作而不是执行重命名操作,这样我可以看到会发生什么,而不必在测试过程中不断重命名文件。 You can change the print() line to a os.rename() call to actually do the renaming. 您可以将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")

Result for my test dir with 4 files in it: 测试目录中包含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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM