2
from importlib.resources import path
import os, shutil, pathlib, fnmatch
import argparse
import time

parser = argparse.ArgumentParser()
parser.add_argument('--src', type=str)
parser.add_argument('--dst', type=str)
parser.add_argument('--pattern', type=str)
args = parser.parse_args()

def move_dir(src: str, dst: str, pattern: str = '*'):
    if not os.path.isdir(dst):
        pathlib.Path(dst).mkdir(parents=True, exist_ok=True)
    for f in fnmatch.filter(os.listdir(src), pattern):
        shutil.move(os.path.join(src, f), os.path.join(dst, f))


move_dir(args.dst(), args.src(),  args.pattern())
time.sleep(5)
move_dir(r"C:\Users\user\Downloads", r"C:\Users\user\Documents\pdf", r"*.pdf")

Creating a script to move files based on pattern in a specific directory. Initially ran into the raw string error when I hard coded and solved by making the output raw as suggested here : How to move a file in Python?

PROBLEM As I tested with the hard code and had to put r before the string I wanted to test moving back from to the old directory and then recopying all over again. (Code was ran correctly once without the 2nd to last 2 lines)

I think I'm now failing to do that when calling the argument string as the error returned shows double backslashes '\'

C:\Users\user\Documents\GitHub\personalUtilities>python downloadOrganizer.py --src "C:\Users\user\Documents\pdf" --dst "C:\Users\user\Downloads" --pattern "*.pdf"  
usage: downloadOrganizer.py [-h] [--src SRC] [--dst DST] [--pattern PATTERN]
downloadOrganizer.py: error: argument --src: invalid path value: 'C:\\Users\\user\\Documents\\pdf'

I see a few articles on making a class to check if the directory exists but that wouldn't solve my problem if I'm passing the wrong string type and any article about this in the subject seems to be answering a different question or solving something else.

So whats the proper way to pass the source and destination directory strings from argparse? Tried changing the type to path for src and dst but didn't change anything. tried adding r to the arg in the cli before the quote string that just made the directory extra wrong!

  • 1
    instead of `move_dir(args.dst(), args.src(), args.pattern())` can you try `move_dir(args.dst, args.src, args.pattern)` – Nandha May 08 '22 at 13:45
  • The double slash is just how Python *displays* a string value containing a backslash. I cannot reproduce your error with the code shown. (`args.dst()` should be `args.dst`, though, and the same for the other attributes of `args`.) – chepner May 08 '22 at 13:46
  • Of course something simple. Thanks for pointing that out. – Discipleofaslan May 08 '22 at 14:03

0 Answers0