脚本如何实现文件内容格式化

wen 实用脚本 1

本文目录导读:

脚本如何实现文件内容格式化

  1. JSON 格式化
  2. XML 格式化
  3. 代码格式化 (Python)
  4. 文本通用格式化
  5. CSV 格式化
  6. 完整的命令行格式化工具
  7. Shell 脚本 - 使用已安装的工具
  8. 使用建议

格式化的方法取决于具体需求和文件类型,下面介绍几种常见的脚本实现方式:

JSON 格式化

Python 脚本

import json
def format_json(input_file, output_file):
    with open(input_file, 'r') as f:
        data = json.load(f)
    with open(output_file, 'w') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
# 使用示例
format_json('input.json', 'output.json')

Shell 脚本 (使用 jq)

#!/bin/bash
# 需要安装 jq: apt install jq 或 brew install jq
cat input.json | jq . > output.json
# 或直接修改原文件
jq . input.json > tmp.json && mv tmp.json input.json

XML 格式化

Python 脚本

import xml.dom.minidom
def format_xml(input_file, output_file):
    with open(input_file, 'r') as f:
        xml_content = f.read()
    dom = xml.dom.minidom.parseString(xml_content)
    pretty_xml = dom.toprettyxml(indent='  ')
    with open(output_file, 'w') as f:
        f.write(pretty_xml)
# 使用示例
format_xml('input.xml', 'output.xml')

代码格式化 (Python)

使用 autopep8

import autopep8
def format_python(input_file, output_file):
    with open(input_file, 'r') as f:
        code = f.read()
    formatted_code = autopep8.fix_code(code)
    with open(output_file, 'w') as f:
        f.write(formatted_code)
# 使用示例
format_python('script.py', 'formatted_script.py')

文本通用格式化

Python 脚本 - 去除多余空格和空行

def format_text(input_file, output_file):
    with open(input_file, 'r') as f:
        lines = f.readlines()
    # 去除每行首尾空格,删除空行
    formatted_lines = [line.strip() for line in lines if line.strip()]
    with open(output_file, 'w') as f:
        f.write('\n'.join(formatted_lines))
# 使用示例
format_text('input.txt', 'output.txt')

CSV 格式化

Python 脚本

import csv
def format_csv(input_file, output_file):
    with open(input_file, 'r') as f:
        reader = csv.reader(f)
        data = list(reader)
    # 去除空行和空格
    cleaned_data = [[cell.strip() for cell in row] for row in data if any(cell.strip() for cell in row)]
    with open(output_file, 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerows(cleaned_data)
# 使用示例
format_csv('input.csv', 'output.csv')

完整的命令行格式化工具

Python 脚本 - 支持多种格式

#!/usr/bin/env python3
import argparse
import sys
def format_file(input_file, output_file, format_type):
    format_functions = {
        'json': format_json,
        'xml': format_xml,
        'text': format_text,
        'csv': format_csv
    }
    if format_type in format_functions:
        format_functions[format_type](input_file, output_file)
    else:
        print(f"不支持的文件格式: {format_type}")
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='文件格式化工具')
    parser.add_argument('input', help='输入文件路径')
    parser.add_argument('-o', '--output', help='输出文件路径')
    parser.add_argument('-f', '--format', choices=['json', 'xml', 'text', 'csv'], 
                       default='text', help='文件格式')
    args = parser.parse_args()
    format_file(args.input, args.output or args.input, args.format)

Shell 脚本 - 使用已安装的工具

#!/bin/bash
format_file() {
    local file=$1
    local ext="${file##*.}"
    case $ext in
        json)
            jq . "$file" > temp.json && mv temp.json "$file"
            ;;
        xml)
            xmllint --format "$file" > temp.xml && mv temp.xml "$file"
            ;;
        py)
            autopep8 --in-place "$file"
            ;;
        *)
            echo "不支持的文件格式: $ext"
            return 1
            ;;
    esac
}
# 使用示例
format_file "example.json"

使用建议

  1. 选择正确工具:根据文件类型选择合适的格式化方法
  2. 备份原文件:格式化前建议备份,防止意外数据丢失
  3. 批量处理:可使用 glob 模块或 find 命令处理多个文件
  4. 错误处理:添加异常处理,防止格式化失败

需要根据具体需求选择合适的方式,如果需要处理特定格式,请提供更多细节,我可以给出更针对性的方案。

抱歉,评论功能暂时关闭!