-1

I'm trying to implement a python script alowwing me to generate a file "file_modified" based on a the argument given to the script

My script is working fine, but now i would like to implement a "recursive" option similar to "rm -r" : the goal is to give a folder (containing n files) as an argument to my script, and generated n new files based on this folder.

#!/usr/bin/python

''' Python tools to blabla
'''

import argparse
from datetime import datetime
import sys
import pandas as pd

EXTENSION="_friendly_excel"
FILETYPE=".csv"


def get_args():
    '''This function parses and return arguments passed in'''
    # Assign description to the help doc
    parser = argparse.ArgumentParser(
    description='python command to transform a former LPBM .csv file to an excel friendly one')

    # Add arguments
    parser.add_argument(
        "file_csv", help="file you wish to convert")
    parser.add_argument('-f', "--filename", type=str, required=False, help="specify a name for the output file")

    # Assign args to variables
    args = parser.parse_args()

    file_csv=args.file_csv
    filename=args.filename

    # Return all variable values
    return file_csv, filename


if __name__ == "__main__":
# Run get_args()
# get_args()

# Match return values from get_arguments()
# and assign to their respective variables
    file_csv, filename = get_args()

#name of the file : 
    if filename:
        filename=filename+FILETYPE
    else:
        filename=file_csv[:-4:]+EXTENSION+FILETYPE

# Print the values
    print "\nfile you wish to convert : %s \n" % file_csv

#opening the file as a dataframe
    try:
        df = pd.read_csv(file_csv, sep=';', parse_dates=['date-time'])
    except:
        print "\nfailed to load the dataframe : are you sure your file is an LPBM generated one ?\n"
        exit()

#saving the modified dataframe with correct date format and decimal
    df.to_csv(filename, date_format='%d/%m/%Y %H:%M:%S', sep=';', decimal=',', index=False)
    print "le fichier %s a bien ete cree" % filename
Julie96
  • 331
  • 1
  • 15
  • 2
    Your question is too broad to be answered IMO. You need to show your work and ask something more specific about it. – goodvibration Jun 19 '19 at 12:49
  • 1
    don't see a reason for recursion. just use `os.listdir()`... – Tomerikoo Jun 19 '19 at 12:49
  • 1
    [os.walk](https://docs.python.org/3/library/os.html#os.walk)? – Ocaso Protal Jun 19 '19 at 12:49
  • 1
    https://docs.python.org/2/library/argparse.html for parsing the recursive option and os.walk as above for recursively going through the dir – Alan Kavanagh Jun 19 '19 at 12:50
  • Possible duplicate of [Basics of recursion in Python](https://stackoverflow.com/q/30214531/608639), [How can I build a recursive function in python?](https://stackoverflow.com/q/479343/608639), etc. – jww Jun 19 '19 at 15:54

1 Answers1

0

I use this simple code snippet for most of my recusions.

def locate(patterns, root=os.curdir, recursive=True):
    """ locate 
    patterns: array; ['*.txt']
    root: str; 
    recursive: bool
    """
    folder = os.path.expanduser(root) if root.startswith('~') else root
    folder = os.path.abspath(folder)

    if not os.path.exists(folder) or not os.path.isdir(folder):
        raise ValueError('{} ({})'.format('Not a folder:', folder))

    for pattern in patterns:   
        if recursive:
            for path, _, files in os.walk(folder, followlinks=True):
                for filename in fnmatch.filter(files, pattern):
                    yield os.path.join(path, filename)
        else:
            for filename in fnmatch.filter(os.listdir(folder), pattern):
                yield os.path.join(folder, filename)

for file in locate(['*.txt']):
    print(file)
alexrjs
  • 546
  • 8
  • 15