J.Doe
J.Doe

Reputation: 21

Code that generates a random 10 digit filename and creates the file

I tried using:

import random
filenamemaker = random.randint(1,1000)

all help would be great thanks :)

Upvotes: 2

Views: 983

Answers (3)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160407

The simplest way would be with string.digits and random.sample. You could also use the with statement with an empty pass in it if don't plan on using the file and automatically want it closed:

from string import digits
from random import sample 

with open("".join(sample(digits, 10)), 'w'): 
    pass

This is equivalent to:

filename = "".join(sample(digits, 10)) 
f = open(filename, 'w')
f.close()

On consecutive calls, this generates filenames such as:

3672945108  6298517034

Upvotes: 3

brianpck
brianpck

Reputation: 8254

randint takes two arguments: a lower and upper (inclusive) bound for the generated number. Your code will generate a number between 1 and 1000 (inclusive), which could be anywhere from 1 to 4 digits.

This will generate a number between 1 and 9999999999:

>>> n = random.randint(1, 9999999999)

You will then want to pad it with zero's and make it a string, in case it is less than 10 digits:

>>> filename = str(n).zfill(10)

You can then open this and write to it:

with open(filename + '.txt', 'w') as f:
    # do stuff
    pass

Upvotes: 0

Efferalgan
Efferalgan

Reputation: 1701

import random

filename = ""
for i in range(10):
    filename += str(random.randint(0,9))

f = open(filename + ".txt", "w")

Upvotes: 0

Related Questions