1

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?

3
  • What is the problem to calculate default later in case if argument haven't been passed? Commented Jan 31, 2020 at 9:20
  • The parser.parse_args().dir expression 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. Commented Jan 31, 2020 at 17:56
  • stackoverflow.com/questions/60000280/… asked the same thing, just minutes earlier. Commented Jan 31, 2020 at 17:58

1 Answer 1

1

Is there a way to get information about the previous argument without parsing it?

No. Not the info you're searching for, at least. To know what the value given for one of the arguments is, you need to parse the arguments.

The way to implement the default behavior you want is via a flag value meaning "process them all". For example:

parser.add_argument('--num', type=int, default=None),
                        help='number of files to rename')

# then in your code, after you parse the arguments:

if args.num is not None:
  # process just num
else:
  # process all the files
Sign up to request clarification or add additional context in comments.

2 Comments

I was hoping there is a way without using another if else. Thanks for the answer.
ifs are cheap, parsing a string for arguments is not. Nothing bad in using control flow!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.