如何在python脚本上实现“递归”选项

2024-04-20 14:31:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图实现一个python脚本,让我根据给定给脚本的参数生成一个文件“file\u modified”

我的脚本运行得很好,但现在我想实现一个类似于“rm-r”的“递归”选项:目标是为我的脚本提供一个文件夹(包含n个文件)作为参数,并基于这个文件夹生成n个新文件。你知道吗

#!/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

Tags: and文件csvthetoimport脚本parser
1条回答
网友
1楼 · 发布于 2024-04-20 14:31:09

我用这个简单的代码片段来处理我的大部分回避

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)

相关问题 更多 >