0

I am looking for a way to check if an input string given by a user could be a valid file name for an output file, lets say a gif.

The user may provide different kinds of input, e.g., they may provide a full path like a/b/c.gif or just a directory a/b or a/b/. I can check these using os.path.isdir(user_path) and os.path.isdir(os.path.dirname(user_path)).

How should I check if I just receive a file name without a directory? I could do something like not os.path.dirname(user_path) and user_path.endswith('.gif') but that would allow still allow a lot of unwanted characters etc.

I am sure there is a neater way to check this. Looking forward to your solution =)

EDIT: at the time I am trying to check the user input, I do not have access to the full path, I will later write to - have to determine the parent directory first. So a solution without touching the file or similar would be preferred.

Nyps
  • 831
  • 1
  • 14
  • 26
  • 1
    Does [this](https://stackoverflow.com/a/34102855/20121320) answer your question? – Florent Monin Feb 27 '23 at 13:25
  • 1
    I think you might find your answer on https://stackoverflow.com/questions/8686880/validate-a-filename-in-python at least it solved my problem in the past ! – GoodErnest64 Feb 27 '23 at 13:27
  • @FlorentMonin the answer you are referring to helps me to solve it. I do not really have access to the full path at the time I want to validate the input. But I can create a dummy path just from the filename. Still cannot believe that there is no library for that though.. – Nyps Feb 27 '23 at 13:47

0 Answers0