Generate a txt file with unique name in python

devsuggest

Dev Suggest

Posted on August 15, 2022

Generate a txt file with unique name in python

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!!")
Enter fullscreen mode Exit fullscreen mode

Thanks for reading.
For more question and answer visit DevSuggest

💖 💪 🙅 🚩
devsuggest
Dev Suggest

Posted on August 15, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related