1
import time

a = 0
amount = 1
while a < 100:
    userfile = 'random{}'.format(amount)
    file = open(userfile, 'a')
    amount += 1
    time.sleep(0.2)
    print(userfile)
    a += 1

I've made a program that creates files with a fixed file name. I'm trying to make it so the file name is a randomly generated set of letters but I don't know quite how to apply the random function to it.

3 Answers3

2

The tempfile module provides just what you want:

import tempfile

random_filename = tempfile.mktemp(dir="")

Sample output: tmp4STAXd

The method supports some helpful arguments that you can checkout in the docs.

sirfz
  • 4,097
  • 23
  • 37
0

You could use something like this :

import string
import random

N = 10
print ''.join(random.SystemRandom().choice(string.ascii_letters) for _ in range(N)) #=> izWIzBXltM or AZlkWOoTGY or ...

Use

print ''.join(random.SystemRandom().choice(string.ascii_lowercase) for _ in range(N))

If you need lowercase only.

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
0

You can use string.ascii_letters to get list of letters and random.choice() to select random letter from list. If you use for and range() then you can get many random letters and later join() them into string.

import string
import random

letters = [random.choice(string.ascii_letters) for x in range(10)]

filename = ''.join(letters)

print(filename)

Docs: string, random

You have also string.ascii_lowercase, string.digits, etc. so you can use ie.

string.ascii_lowercase + string.digits
furas
  • 134,197
  • 12
  • 106
  • 148