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

wen 实用脚本 1

本文目录导读:

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

  1. Python 实现文件导入
  2. JavaScript (Node.js) 实现文件导入
  3. Shell 脚本实现
  4. 完整示例:Python 文件导入工具
  5. Web 前端文件导入
  6. 最佳实践建议

Python 实现文件导入

基础文件读取

# 读取整个文件
with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)
# 按行读取
with open('example.txt', 'r', encoding='utf-8') as file:
    for line in file:
        print(line.strip())

CSV 文件导入

import csv
# 读取 CSV 文件
with open('data.csv', 'r', encoding='utf-8') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
# 读取为字典格式
with open('data.csv', 'r', encoding='utf-8') as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row['name'], row['age'])

JSON 文件导入

import json
# 读取 JSON 文件
with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
    print(data)

JavaScript (Node.js) 实现文件导入

同步读取

const fs = require('fs');
// 同步读取文件
try {
    const content = fs.readFileSync('example.txt', 'utf8');
    console.log(content);
} catch (err) {
    console.error('文件读取失败:', err);
}

异步读取

const fs = require('fs').promises;
// 异步读取文件
async function readFile() {
    try {
        const content = await fs.readFile('example.txt', 'utf8');
        console.log(content);
    } catch (err) {
        console.error('文件读取失败:', err);
    }
}
readFile();

Shell 脚本实现

Bash 读取文件

#!/bin/bash
# 读取整个文件
content=$(cat example.txt)
echo "$content"
# 按行读取
while IFS= read -r line; do
    echo "Line: $line"
done < example.txt

带错误处理

#!/bin/bash
filename="example.txt"
if [ -f "$filename" ]; then
    while IFS= read -r line; do
        echo "$line"
    done < "$filename"
else
    echo "错误:文件 $filename 不存在"
    exit 1
fi

完整示例:Python 文件导入工具

import os
import json
import csv
from typing import Any, Optional
class FileImporter:
    """文件导入器"""
    def __init__(self, filepath: str):
        self.filepath = filepath
        self.extension = os.path.splitext(filepath)[1].lower()
    def import_text(self, encoding: str = 'utf-8') -> str:
        """导入文本文件"""
        try:
            with open(self.filepath, 'r', encoding=encoding) as file:
                return file.read()
        except FileNotFoundError:
            raise FileNotFoundError(f"文件 {self.filepath} 不存在")
        except Exception as e:
            raise Exception(f"读取文件失败: {str(e)}")
    def import_csv(self, delimiter: str = ',', has_header: bool = True) -> list:
        """导入CSV文件"""
        try:
            with open(self.filepath, 'r', encoding='utf-8') as file:
                if has_header:
                    return [row for row in csv.DictReader(file, delimiter=delimiter)]
                else:
                    return [row for row in csv.reader(file, delimiter=delimiter)]
        except Exception as e:
            raise Exception(f"导入CSV失败: {str(e)}")
    def import_json(self) -> Any:
        """导入JSON文件"""
        try:
            with open(self.filepath, 'r', encoding='utf-8') as file:
                return json.load(file)
        except json.JSONDecodeError:
            raise ValueError("JSON格式错误")
        except Exception as e:
            raise Exception(f"导入JSON失败: {str(e)}")
    def import_by_extension(self) -> Optional[Any]:
        """根据文件扩展名自动导入"""
        importers = {
            '.txt': self.import_text,
            '.csv': self.import_csv,
            '.json': self.import_json
        }
        importer = importers.get(self.extension)
        if importer:
            return importer()
        else:
            raise ValueError(f"不支持的文件格式: {self.extension}")
# 使用示例
def main():
    # 创建导入器实例
    importer = FileImporter('data.csv')
    try:
        # 导入CSV文件
        data = importer.import_csv()
        print("CSV数据:", data)
        # 或者根据扩展名自动导入
        auto_importer = FileImporter('config.json')
        config = auto_importer.import_by_extension()
        print("配置数据:", config)
    except Exception as e:
        print(f"导入失败: {e}")
if __name__ == "__main__":
    main()

Web 前端文件导入

HTML + JavaScript

<!DOCTYPE html>
<html>
<head>文件导入</title>
</head>
<body>
    <input type="file" id="fileInput" accept=".txt,.csv,.json">
    <pre id="output"></pre>
    <script>
        document.getElementById('fileInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            const reader = new FileReader();
            reader.onload = function(event) {
                document.getElementById('output').textContent = event.target.result;
            };
            reader.onerror = function() {
                alert('文件读取失败');
            };
            // 根据不同文件类型处理
            if (file.name.endsWith('.json')) {
                reader.readAsText(file);
            } else {
                reader.readAsText(file);
            }
        });
    </script>
</body>
</html>

最佳实践建议

  1. 错误处理:始终添加 try-catch 块处理文件不存在、权限不足等异常
  2. 编码处理:指定正确的字符编码(通常为 UTF-8)
  3. 资源管理:使用 with 语句确保文件正确关闭
  4. 大文件处理:对大文件使用流式处理或分块读取
  5. 路径安全:验证文件路径,防止路径遍历攻击
  6. 性能优化:对于大文件,考虑异步读取或使用缓冲区

选择哪种实现方式取决于你的具体需求:系统类型(后端/前端)、文件格式、性能要求和开发环境。

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