![](/img/trans.png)
[英]How do I check if files in my folder coincide with the file names specified in my .csv file?
[英]Randomize file names in a specified folder
我有一個包含文件的特定文件夾,我需要隨機化它們的名稱。 文件夾位置必須能夠更改,文件名應包含a-z中的6-10個字符。 如何在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 )
另外,在腳本中,您可以讀取新創建目錄的權限。
我將提供與@ 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.