I’m trying to make a system where the user inputs a string which will be made into a directory. How would I check if the string is able to actually make the directory without error. So the user can’t make " " directories, directories with "/\:*?<>|" in them, or any kind of directory that can’t actually be made.
I’ve tried nothing as searching it up on stackoverflow or google returns with no results with what I am looking for.
>Solution :
-
Get the user’s input.
-
Check for invalid characters such as
/:*?<>|.
import os
user_input = input("Enter a directory name: ")
# Function to check if a string is a valid directory name
def is_valid_directory_name(name):
# List of invalid characters
invalid_chars = r'\/:*?<>|'
if any(char in invalid_chars for char in name) or name.isspace():
return False
return True
if is_valid_directory_name(user_input):
try:
# Create the directory
os.mkdir(user_input)
print(f"Directory '{user_input}' created successfully.")
except FileExistsError:
print(f"Directory '{user_input}' already exists.")
except Exception as e:
print(f"An error occurred while creating the directory: {e}")
else:
print("Invalid directory name. Please avoid special characters and spaces.")