Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I check if a String can be made into a valid directory

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  1. Get the user’s input.

  2. 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.")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading