In this tutorial, you will learn how to Generate a txt file with unique name in python.
Generating a random number
To generate random number, randint() function is used.
The randint() method returns an integer number selected element from the specified range.
To create a file in python, open() function is used.
The open() function opens a file, and returns it as a file object.
Code Example
import random
ran_num = random.randint(0,5)
file_name = "random"+str(ran_num);
try:
with open(file_name+'.txt', 'w') as f:
f.write('Create a new text sfile!')
except FileNotFoundError:
print("There is an unknown error!!")
Thanks for reading.
For more question and answer visit DevSuggest
Top comments (0)