Hazim Naufal
Hazim Naufal

Reputation: 7

How to Create New File Everytime I Run The Program?

I want my code to create a new file every time the user registers a new username and password, they'll have their own file which will have all their data into that file.

My current code just re-writes the same file, is there a way to code so it creates a new file each time?

def register():
    print("To Register as a New Customer Create a New Username and Password")

    userDetails = open("user_details" , 'w')
    
    username = input("\nEnter Username: ")
    password = input("Enter Password: ")

    userDetails.write("\nUsername: " + username + "\n")
    userDetails.write("Password: " + password + "\n")

    userDetails.close()
     
register()

Upvotes: 1

Views: 345

Answers (1)

Krishna Chaurasia
Krishna Chaurasia

Reputation: 9572

You can use the uuid module to generate a unique id for every user and use that as a file name:

import uuid

def register():

    print("To Register as a New Customer Create a New Username and Password")

    username = input("\nEnter Username: ")
    password = input("Enter Password: ")

    file_name = f"{username}-{uuid.uuid4()}"

    userDetails = open(file_name , 'w')
    userDetails.write("\nUsername: " + username + "\n")
    userDetails.write("Password: " + password + "\n")
    userDetails.close()
    
register()

Ideally, you could just create a single file with details of all users as suggested by Irfan and have a unique id per user to distinguish them.

Upvotes: 1

Related Questions