Skip to content

Instantly share code, notes, and snippets.

@jiminj
Last active April 6, 2022 14:59
Show Gist options
  • Save jiminj/06be93e397fab6a109708e579789a98b to your computer and use it in GitHub Desktop.
Save jiminj/06be93e397fab6a109708e579789a98b to your computer and use it in GitHub Desktop.
collect and rename first csv files found under given subdirectories
import argparse
import os
import glob
import shutil
def dir_path(path):
if os.path.isdir(path):
return path
else:
raise argparse.ArgumentTypeError(f"{path} is not a valid path")
parser = argparse.ArgumentParser(description='Collect csv files under subdirectories')
parser.add_argument('fileroot', nargs='?', type=dir_path, help='working path', default=os.getcwd())
fileroot = parser.parse_args().fileroot
subdirs= [ d for d in os.listdir(fileroot) if os.path.isdir(os.path.join(fileroot, d))]
for sd in subdirs:
csvs = glob.glob(os.path.join(fileroot, sd, '**', '*.csv'), recursive=True)
#if not empty
if(csvs):
copy_src = os.path.abspath(csvs[0]) # copy the first csv file found to the working directory
copy_dest = os.path.join(os.getcwd(), sd + '.csv')
print(f'copy file {copy_src} to {copy_dest}')
shutil.copyfile(copy_src, copy_dest)
@nufrancis
Copy link

LOVE YOU

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment