I am trying to write a simple python script that will rename files in the directory, using naming conventions. To do this, I need a path to the directory and the number of files to process. By default, I want the script to rename all files in the directory.
import os
import sys
import shutil
import argparse
parser = argparse.ArgumentParser(description='Rename files in the directory, using naming conventions')
parser.add_argument('name', help='first part of a new name')
parser.add_argument('--dir', default=os.getcwd(), help='directory containing files')
parser.add_argument('--num', type=int, default = len([file for file in os.listdir(parser.parse_args().dir)]),
help='number of files to rename')
args = parser.parse_args()
And here is an output for just '-h' argument:
usage: rename.py [-h] [--dir DIR] name
Rename files in the directory, using naming conventions
positional arguments:
name first part of a new name
optional arguments:
-h, --help show this help message and exit
--dir DIR directory containing files
It seems to me that the last argument is not being processed due to parser.parse_args().dir.
Is there a way to get information about the previous argument without parsing it?
parser.parse_args().direxpression is catching the-h, printing the help for the parser as defined so far, and exiting. Post parsing handling of cases like this is easier and more reliable.