Creating unique or random file names in Python is useful when saving temporary files, uploading user content, or avoiding name collisions. Here are five different techniques to generate random file names using Python.
1. Using uuid.uuid4()
import uuid
filename = str(uuid.uuid4()) + ".txt"
print(filename)
2. Using secrets
import secrets
import string
chars = string.ascii_letters + string.digits
filename = ''.join(secrets.choice(chars) for _ in range(12)) + ".txt"
print(filename)
3. Using tempfile.NamedTemporaryFile()
import tempfile
with tempfile.NamedTemporaryFile(delete=False) as tmp:
print(tmp.name)
4. Using random
and time
import random
import time
filename = f"{int(time.time())}_{random.randint(1000, 9999)}.txt"
print(filename)
5. Using hashlib
with timestamp or UUID
import hashlib
import time
unique_input = str(time.time()).encode()
filename = hashlib.sha256(unique_input).hexdigest()[:16] + ".txt"
print(filename)
Conclusion
Depending on your needs—security, uniqueness, simplicity, or temporary use—Python offers multiple ways to generate random file names. Consider context when choosing the right approach for your application.
No comments:
Post a Comment