'How to check whether a command line argument is in a specified format?

I want my program to check if a command line argument is in a specified format.

Here is how the arguments are passed:

python3 <file.py> documents/folder1/file_1.txt

Here is the code that gets the arguments:

import sys
f = sys.argv[1]

I want to check if f is in the format of

documents/folder1/<filename>


Solution 1:[1]

You could write any string manipulation checks like

import sys
f = sys.argv[1]

if len(f.split('/')) == 3: # if it's in nested format of depth 3
  # do something

if f.endswith(".txt") # If argument has a text file in the end

if f.startswith("documents/folder1/") # check whether the exact path is present or not

For the help part, you could use argparse too:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("text_file", help="argument having text file. Should be in format 'documents/folder1/<filename>'",)
args = parser.parse_args()
f = args.text_file

then use this variable f (which is of type string) as you wish

Solution 2:[2]

You can use regular expression to do it:

import re

prog = re.compile("^(\w+/)*\w+(\.\w+)?$")
result1 = prog.search("documents/folder1/file_1.txt")
result2 = prog.search("documents/folder2/test")
result3 = prog.search("ab#$")

print(bool(result1)) # True
print(bool(result2)) # True
print(bool(result))  # False

The pattern I wrote assumes your filenames and directory names are composed of ascii letters, digits, or underline. It also allows filenames without an extension. You can twick it based on the file system you are using, which determines what characters are allowed, and the specific pattern you have in mind.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Deshwal
Solution 2 AlpacaMax