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

求可作为计划任务的ANSI转UTF-8编码CSV文件转换脚本

可行,以下是不同平台的可自动化转换脚本

Windows PowerShell 脚本

适合Windows环境,可直接添加到计划任务中执行。脚本会遍历指定目录下的ANSI编码CSV文件,转换为UTF-8(带BOM,适配部分依赖BOM识别UTF-8的Windows应用),可按需选择保留原文件或替换。

# 设置目标共享目录路径
$targetDir = "C:\Path\To\Shared\Folder"
# 遍历目录下所有.csv文件
Get-ChildItem -Path $targetDir -Filter *.csv | ForEach-Object {
    # 读取ANSI编码文件(默认Windows-1252,若你的ANSI为GBK/GB2312等,修改Encoding参数即可)
    $content = Get-Content -Path $_.FullName -Encoding Default
    # 写入UTF-8带BOM的文件,需无BOM则改用UTF8NoBOM
    $content | Set-Content -Path $_.FullName -Encoding UTF8
    # 可选:保留原文件,转换后生成带_utf8后缀的新文件
    # $newPath = Join-Path $_.DirectoryName "$($_.BaseName)_utf8.csv"
    # $content | Set-Content -Path $newPath -Encoding UTF8
}

计划任务设置步骤

  1. 打开「任务计划程序」,创建新任务
  2. 触发器设置为所需频率(如每小时、文件创建时)
  3. 操作选择「启动程序」,程序/脚本填powershell.exe,添加参数填-ExecutionPolicy Bypass -File "C:\Path\To\Your\Script.ps1"
  4. 确保执行账户拥有共享目录的读写权限

Linux/macOS Bash 脚本

适合类Unix环境,可通过cron设置定时任务。利用系统默认自带的iconv工具完成编码转换。

#!/bin/bash
# 设置目标共享目录路径
TARGET_DIR="/path/to/shared/folder"
# 遍历目录下所有.csv文件
for file in "$TARGET_DIR"/*.csv; do
    # 转换编码:从Windows-1252(ANSI)转UTF-8,覆盖原文件;需保留原文件则修改输出路径
    iconv -f Windows-1252 -t UTF-8 "$file" -o "$file"
    # 可选:保留原文件,生成带_utf8后缀的新文件
    # iconv -f Windows-1252 -t UTF-8 "$file" > "${file%.csv}_utf8.csv"
done

Cron 任务设置

  1. 执行crontab -e编辑定时任务
  2. 添加执行规则(如每小时执行一次):0 * * * * /path/to/your/script.sh
  3. 保存退出,确保脚本拥有执行权限(chmod +x script.sh)

Python 跨平台脚本

适配多平台环境,只要安装Python即可运行,编码识别更灵活,可自动检测ANSI编码(需提前安装chardet库)。

import os
import chardet

# 先安装依赖:pip install chardet
target_dir = "/path/to/shared/folder"  # Windows环境用"C:\\Path\\To\\Shared\\Folder"

for filename in os.listdir(target_dir):
    if filename.endswith(".csv"):
        file_path = os.path.join(target_dir, filename)
        # 自动检测文件编码
        with open(file_path, 'rb') as f:
            detect_result = chardet.detect(f.read())
        ansi_encoding = detect_result['encoding']
        # 读取并转换为UTF-8格式
        with open(file_path, 'r', encoding=ansi_encoding) as f:
            content = f.read()
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        # 可选:保留原文件,生成带_utf8后缀的新文件
        # new_file_path = os.path.join(target_dir, f"{os.path.splitext(filename)[0]}_utf8.csv")
        # with open(new_file_path, 'w', encoding='utf-8') as f:
        #     f.write(content)

计划任务设置

  • Windows:同PowerShell脚本,计划任务中启动python.exe,参数填"C:\Path\To\Your\Script.py"
  • Linux/macOS:同Bash脚本,Cron任务中执行python3 /path/to/your/script.py

注意事项

  • 若你的ANSI编码为GBK/GB2312等非Windows-1252格式,需对应修改脚本中的编码参数
  • 首次转换前建议备份文件,避免数据丢失
  • 可扩展脚本逻辑,比如仅转换指定时间范围内的新文件(通过文件修改时间判断)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 18:23:00