脚本如何实现文件内容导出功能

wen 实用脚本 3

本文目录导读:

脚本如何实现文件内容导出功能

  1. Python 实现
  2. JavaScript (Node.js) 实现
  3. Bash/Shell 实现
  4. 功能增强版本
  5. 前端浏览器实现

Python 实现

基本文件导出

def export_file(source_path, target_path):
    """复制文件内容到新位置"""
    try:
        with open(source_path, 'r', encoding='utf-8') as source:
            content = source.read()
        with open(target_path, 'w', encoding='utf-8') as target:
            target.write(content)
        print(f"文件已导出到: {target_path}")
    except FileNotFoundError:
        print("源文件不存在")
    except Exception as e:
        print(f"导出失败: {e}")
# 使用示例
export_file("source.txt", "exported_file.txt")

按行导出(适合大文件)

def export_file_lines(source_path, target_path, start_line=0, end_line=None):
    """按行范围导出文件"""
    try:
        with open(source_path, 'r', encoding='utf-8') as source:
            lines = source.readlines()
        if end_line is None:
            end_line = len(lines)
        with open(target_path, 'w', encoding='utf-8') as target:
            for line in lines[start_line:end_line]:
                target.write(line)
        print(f"成功导出 {end_line - start_line} 行到 {target_path}")
    except Exception as e:
        print(f"导出失败: {e}")
# 使用示例:导出第10-30行
export_file_lines("large_file.txt", "partial_export.txt", 9, 30)

JavaScript (Node.js) 实现

基本文件导出

const fs = require('fs');
const path = require('path');
function exportFile(sourcePath, targetPath) {
    try {
        // 创建目标目录(如果不存在)
        const targetDir = path.dirname(targetPath);
        if (!fs.existsSync(targetDir)) {
            fs.mkdirSync(targetDir, { recursive: true });
        }
        // 读取源文件并写入目标文件
        const content = fs.readFileSync(sourcePath, 'utf8');
        fs.writeFileSync(targetPath, content, 'utf8');
        console.log(`文件已导出到: ${targetPath}`);
    } catch (error) {
        console.error('导出失败:', error);
    }
}
// 使用示例
exportFile('./source.txt', './exports/exported_file.txt');

异步版本

const fs = require('fs').promises;
async function exportFileAsync(sourcePath, targetPath) {
    try {
        const content = await fs.readFile(sourcePath, 'utf8');
        await fs.writeFile(targetPath, content, 'utf8');
        console.log(`文件已导出到: ${targetPath}`);
    } catch (error) {
        console.error('导出失败:', error);
    }
}
// 使用示例
exportFileAsync('./source.txt', './exports/exported_file.txt').then(() => {
    console.log('导出完成');
});

Bash/Shell 实现

基础文件复制

#!/bin/bash
# 函数:导出文件
export_file() {
    local source=$1
    local target=$2
    if [ ! -f "$source" ]; then
        echo "错误:源文件 $source 不存在"
        return 1
    fi
    # 创建目标目录(如果需要)
    mkdir -p "$(dirname "$target")"
    # 复制文件
    cp "$source" "$target"
    if [ $? -eq 0 ]; then
        echo "文件已导出到: $target"
    else
        echo "导出失败"
        return 1
    fi
}
# 调用函数
export_file "source.txt" "/path/to/export/exported_file.txt"

高级导出(带过滤)

#!/bin/bash
# 函数:导出指定模式的行到新文件
export_filtered_lines() {
    local source=$1
    local target=$2
    local pattern=$3
    if [ ! -f "$source" ]; then
        echo "错误:源文件 $source 不存在"
        return 1
    fi
    # 使用 grep 过滤并导出
    grep "$pattern" "$source" > "$target"
    local line_count=$(wc -l < "$target")
    echo "已导出 $line_count 行匹配 '$pattern' 的内容到 $target"
}
# 使用示例:导出包含 "ERROR" 的行
export_filtered_lines "app.log" "errors.txt" "ERROR"

功能增强版本

Python 带进度条和格式转换

import os
from pathlib import Path
def smart_export(source_path, target_path, encoding='utf-8', 
                 overwrite=False, backup=False):
    """
    智能文件导出函数
    """
    source = Path(source_path)
    target = Path(target_path)
    # 检查源文件
    if not source.exists():
        raise FileNotFoundError(f"源文件不存在: {source_path}")
    # 检查目标文件
    if target.exists() and not overwrite:
        if backup:
            # 自动备份
            backup_path = target.with_suffix(target.suffix + '.bak')
            target.rename(backup_path)
            print(f"已备份原文件到: {backup_path}")
        else:
            raise FileExistsError(f"目标文件已存在: {target_path}")
    # 创建目标目录
    target.parent.mkdir(parents=True, exist_ok=True)
    # 读取并处理文件
    file_size = source.stat().st_size
    processed_size = 0
    with open(source, 'r', encoding=encoding) as src:
        content = src.read()
    # 写入目标文件
    with open(target, 'w', encoding=encoding) as dst:
        dst.write(content)
    print(f"✅ 导出完成: {source.name} → {target}")
    print(f"   文件大小: {os.path.getsize(target_path) / 1024:.2f} KB")
# 使用示例
smart_export(
    "source.txt", 
    "./exports/new_file.txt",
    overwrite=True,
    backup=True
)

前端浏览器实现

// 浏览器中下载文件
function downloadFile(content, filename, contentType = 'text/plain') {
    const blob = new Blob([content], { type: contentType });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
}
// 使用示例
downloadFile("这是要导出的内容", "exported_file.txt");

这些方案可以根据你的具体需求选择使用,需要我详细解释某个特定实现吗?

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