Last active
April 6, 2022 14:59
-
-
Save jiminj/06be93e397fab6a109708e579789a98b to your computer and use it in GitHub Desktop.
collect and rename first csv files found under given subdirectories
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
LOVE YOU