Last active
January 28, 2020 22:31
-
-
Save i5ar/7bccccc695c3a18539ea19cb268abd02 to your computer and use it in GitHub Desktop.
Make directories from a CSV file
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
#!/usr/bin/env python | |
# __ __ | |
# ___________ ______ ___ / /______/ (_)____ | |
# / ___/ ___/ | / / __ __ \/ //_/ __ / / ___/ | |
# / /__(__ )| |/ / / / / / / < / /_/ / / / | |
# \___/____/ |___/_/ /_/ /_/_/|_|\____/_/_/ | |
""" | |
Make directories from a CSV file. | |
Basic usage: | |
$ python csvmkdir.py file.csv | |
The CSV file should look something like this: | |
Rossi Mario | |
Esposito Giuseppe | |
""" | |
import csv | |
import argparse | |
from pathlib import Path | |
__title__ = 'csvmkdir' | |
__description__ = 'Make directories from a CSV file.' | |
__version__ = '1.0.0' | |
__author__ = 'i5ar' | |
__license__ = 'MIT' | |
__copyright__ = 'Copyright 2020 i5ar' | |
parser = argparse.ArgumentParser(description='Make dirs from a CSV file') | |
parser.add_argument('file', help='CSV file') | |
parser.add_argument('--header', action='store_true', help='has header') | |
parser.add_argument('--index', action='store_true', help='use index') | |
args = parser.parse_args() | |
csv_file_path = Path(args.file) | |
has_header = args.header | |
use_index = args.index | |
def make_directory(path): | |
try: | |
if not path.exists(): | |
path.mkdir() | |
except OSError as err: | |
print(err) | |
def main(): | |
with open(csv_file_path, newline='', encoding='utf-8') as csvfile: | |
dialect = csv.Sniffer().sniff(csvfile.read(1024)) | |
csvfile.seek(0) | |
reader = csv.reader(csvfile, dialect) | |
outer_dir_path = Path(csv_file_path.stem) | |
make_directory(outer_dir_path) | |
if has_header: | |
next(reader) # skip header | |
for i, row in enumerate(reader): | |
index = i+1 # start directory indexing from 1 instead of 0 | |
first_col = row[0] # get first column values | |
lower_fullname = first_col.strip().lower() # into "cognome nome" | |
inner_dir_name = lower_fullname.replace( | |
" ", "_") # into "cognome_nome" | |
if use_index: | |
inner_dir_name = '{:02d}-{}'.format( | |
index, inner_dir_name) # into "00-cognome_nome" | |
make_directory(outer_dir_path / inner_dir_name) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment