Reputation: 19
I am trying to randomize filenames in a directory. The problem is that the extension disappears after renaming. What do I need to change in order to new filenames have their original extensions?
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)
randomize_files("/tmp/tset21")
Upvotes: 0
Views: 222
Reputation: 2422
Well that's normal: if you rename file "abc.txt" to "efg", you remove the extension. os.rename
is the equivalent of mv
in bash
Instead, what you can do is something like that:
extension = path.split('.')[-1]
new_name = generate_random_name()
os.rename(path, new_name + '.' + extension)
Upvotes: 2