Listing file names present in a directory without using import os

57 Views Asked by At

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 :)

3

There are 3 best solutions below

1
Kelly Bundy On BEST ANSWER

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!!")

Attempt This Online!

0
Guy On

You can use pathlib to check if a specific file exists

from pathlib import Path

...

title = new_username + '.txt'  # Creating title of the file
is_exists = Path(title).exists() 
if not is_exists:
    with open(title, 'w') as file:
        file.write(new_password)
0
Kastet6398 On

You can use the native python open() function, and then try to open it in read mode. If it doesn't exist, it'll throw an exception and you can catch it, and if it occurred, the file doesn't exist, and everything is OK.

Here's the example code:

new_username = str(input('Please choose a username: '))

title = new_username + '.txt'
try:
    open(title, 'r')
    print("Username already exists. Choose a different one.")
except FileNotFoundError:
    new_password = str(input('Please choose a password: '))
    print("Good Choice!")
    file = open(title, 'w')
    file.write(new_password)
    file.close()
    print("User successfully created!")