You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python脚本实现类似rm -r的递归选项?

Modified Script with Recursive Folder Support

Here's an updated version of your script that adds recursive folder processing (similar to rm -r) while keeping all your original functionality intact:

#!/usr/bin/python
''' Python tools to convert LPBM generated .csv files to Excel-friendly format '''
import argparse
from datetime import datetime
import sys
import pandas as pd
import os

EXTENSION = "_friendly_excel"
FILETYPE = ".csv"

def convert_lpbm_csv(input_file, output_filename=None):
    """Convert a single LPBM CSV file to Excel-friendly format"""
    # Determine output filename
    if output_filename:
        output_file = output_filename + FILETYPE
    else:
        # Use original filename with extension added (more reliable than string slicing)
        base_name = os.path.splitext(input_file)[0]
        output_file = f"{base_name}{EXTENSION}{FILETYPE}"
    
    print(f"\nConverting file: {input_file}")
    
    # Load the CSV into DataFrame
    try:
        df = pd.read_csv(input_file, sep=';', parse_dates=['date-time'])
    except Exception as e:
        print(f"\nFailed to load {input_file}: Are you sure it's an LPBM generated file? Error: {str(e)}")
        return False
    
    # Save the converted CSV
    try:
        df.to_csv(
            output_file,
            date_format='%d/%m/%Y %H:%M:%S',
            sep=';',
            decimal=',',
            index=False
        )
        print(f"Successfully created: {output_file}")
        return True
    except Exception as e:
        print(f"\nFailed to save {output_file}: {str(e)}")
        return False

def find_csv_files(root_path, recursive):
    """Find all CSV files in the given path, optionally recursively"""
    csv_files = []
    if recursive:
        for dirpath, _, filenames in os.walk(root_path):
            for filename in filenames:
                if filename.lower().endswith(FILETYPE):
                    csv_files.append(os.path.join(dirpath, filename))
    else:
        for filename in os.listdir(root_path):
            file_path = os.path.join(root_path, filename)
            if os.path.isfile(file_path) and filename.lower().endswith(FILETYPE):
                csv_files.append(file_path)
    return csv_files

def get_args():
    '''This function parses and return arguments passed in'''
    parser = argparse.ArgumentParser(
        description='Convert LPBM generated .csv files to an Excel-friendly format. Supports single files or folders (with optional recursion).'
    )
    # Update positional arg to accept file OR folder path
    parser.add_argument(
        "path", 
        help="Path to the LPBM .csv file OR folder containing LPBM .csv files"
    )
    parser.add_argument('-f', "--filename", type=str, required=False, 
                        help="Specify a name for the output file (only valid when converting a single file)")
    parser.add_argument('-r', "--recursive", action='store_true', 
                        help="Recursively process all CSV files in subfolders (only valid when converting a folder)")
    args = parser.parse_args()
    return args.path, args.filename, args.recursive

if __name__ == "__main__":
    path, filename, recursive = get_args()
    
    # Handle single file conversion
    if os.path.isfile(path):
        if not path.lower().endswith(FILETYPE):
            print(f"Error: {path} is not a CSV file")
            sys.exit(1)
        convert_lpbm_csv(path, filename)
    # Handle folder conversion
    elif os.path.isdir(path):
        if filename:
            print("Warning: --filename argument is ignored when converting multiple files in a folder")
        csv_files = find_csv_files(path, recursive)
        if not csv_files:
            print(f"No CSV files found in {'and subfolders of ' if recursive else ''}{path}")
            sys.exit(0)
        print(f"Found {len(csv_files)} CSV file(s) to convert")
        success_count = 0
        for file in csv_files:
            if convert_lpbm_csv(file):
                success_count += 1
        print(f"\nConversion complete: {success_count}/{len(csv_files)} files converted successfully")
    # Invalid path case
    else:
        print(f"Error: {path} is not a valid file or folder")
        sys.exit(1)

Key Improvements & Usage:

1. Core New Features

  • Folder Processing: Pass a folder path instead of a single file to convert all CSV files inside
  • Recursive Mode: Add the -r flag to process CSV files in the target folder and all its subfolders
  • Batch Error Handling: If one file fails to convert (e.g., not an LPBM CSV), the script will skip it and continue with others

2. How to Use

Convert a single file (original behavior):

python your_script.py input_file.csv
# Or with custom output name
python your_script.py input_file.csv -f my_custom_output

Convert all CSV files in a folder:

# Only files in the target folder (no subfolders)
python your_script.py /path/to/your/csv_folder
# Include all subfolders (recursive)
python your_script.py /path/to/your/csv_folder -r

3. Other Quality-of-Life Changes

  • More reliable filename handling using os.path.splitext() instead of string slicing
  • Clearer error messages with specific exception details
  • Validation to ensure the input path is a valid file/folder
  • Warning if you try to use the -f flag with a folder (since it doesn't apply to multiple files)

内容的提问来源于stack exchange,提问作者Julie96

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:29:06