I am attempting to create a program allowing new user creation on python. However already created users get overwritten if the name of the new profile is the same as the old one, this is because a new text file is created with the selected username as the title, so the new text file replaces the old one.
Due to restrictions on my system I am unable to use import os
, so I need an alternative method to list all the file names present in a directory or subdirectory, so they can be compared to the new username and cancel the user creation if a file with that name already exists to prevent users being overwritten.
Snippet of my code:
new_username=str(input('Please choose a username : '))
new_password=str(input('Please choose a password : '))
print("Good Choice!")
title=new_username + '.txt' #Creating title of the file
file=open(title,'w') #Creating the file
file.write(new_password) #Adding password to the file
file.close()
print("User succesfuly created!!")
This part all runs fine, I just need a way to prevent it from overwriting other users.
Thank you for your time :)
You can open with mode 'x'
: "open for exclusive creation, failing if the file already exists".
try:
with open(title, 'x') as file:
file.write(new_password)
print("User successfully created!!")
except FileExistsError:
print("User already exists!!")