本文目录导读:

当然可以!我为你整理了几个实用脚本示例,分别适用于不同场景下的批量追加操作,直接复制修改即可使用。
多文件行尾追加(最常用)
Python 脚本
import os
def batch_append_to_files(directory, content, suffix=".txt", recursive=False):
"""
批量在文件末尾追加内容
:param directory: 目标目录
:param content: 要追加的内容
:param suffix: 文件后缀过滤,如 .txt .log .md
:param recursive: 是否递归子目录
"""
if not os.path.exists(directory):
print(f"目录 {directory} 不存在!")
return
# 遍历文件
if recursive:
for root, dirs, files in os.walk(directory):
for f in files:
if f.endswith(suffix):
file_path = os.path.join(root, f)
_append_to_file(file_path, content)
else:
for f in os.listdir(directory):
if f.endswith(suffix):
file_path = os.path.join(directory, f)
_append_to_file(file_path, content)
def _append_to_file(filepath, content):
"""单文件追加操作"""
try:
with open(filepath, 'a', encoding='utf-8') as f:
f.write(content)
print(f"[✓] 已追加: {filepath}")
except Exception as e:
print(f"[✗] 失败 {filepath}: {e}")
# ============ 使用示例 ============
if __name__ == "__main__":
# 给当前目录下所有 .txt 文件末尾加上一行 "---END---"
batch_append_to_files(
directory="./logs", # 改成你的目标目录
content="\n---END---\n", # 要追加的内容(包含换行)
suffix=".txt", # 只处理 .txt 文件
recursive=True # 是否包含子文件夹
)
批量追加内容 + 文件名/时间戳(更智能)
Shell 脚本 (Linux/Mac/WSL)
#!/bin/bash
# 批量给文件追加内容,并自动添加文件名和时间戳
TARGET_DIR="./reports"
APPEND_CONTENT="报告生成时间: $(date '+%Y-%m-%d %H:%M:%S')"
cd "$TARGET_DIR" || exit
for file in *.txt *.log *.md; do
[ -f "$file" ] || continue # 跳过非文件
echo "========================================" >> "$file"
echo "文件名称: $file" >> "$file"
echo "$APPEND_CONTENT" >> "$file"
echo "========================================" >> "$file"
echo "已处理: $file"
done
Windows Batch 脚本 (.bat)
@echo off
setlocal enabledelayedexpansion
set "TARGET_DIR=C:\logs"
set "APPEND_LINE=-- 最后更新于 %DATE% %TIME%"
cd /d "%TARGET_DIR%"
for %%f in (*.txt *.log) do (
echo !APPEND_LINE! >> "%%f"
echo 已追加: %%f
)
echo 批量追加完成!
pause
批量追加 JSON/结构化数据(适合配置文件)
import json
import os
def batch_append_to_json(directory, new_data, suffix=".json"):
"""
批量给 JSON 文件追加键值对
:param new_data: 要追加的数据,如 {"version": "2.0"}
"""
for file in os.listdir(directory):
if not file.endswith(suffix):
continue
file_path = os.path.join(directory, file)
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
# 合并新数据(覆盖或追加)
data.update(new_data)
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(f"[✓] 已更新: {file}")
except Exception as e:
print(f"[✗] 跳过 {file}: {e}")
# 用例如:给所有配置文件增加版本号
batch_append_to_json("./config", {"version": "2.0.1", "last_modified": "2024-01-15"})
高阶:根据模板批量追加差异化内容
# 场景:给不同文件追加不同内容(文件名匹配模板)
import os, glob
def smart_append(directory):
template = {
"error*.log": "\n[ERROR] 系统故障,请检查!\n",
"access*.log": "\n[ACCESS] 时间: 2024-01-15 10:00:00\n",
"debug*.log": "\n[DEBUG] 调用栈: main -> module_a -> func_b\n",
}
for pattern, content in template.items():
for file_path in glob.glob(os.path.join(directory, pattern)):
with open(file_path, 'a', encoding='utf-8') as f:
f.write(content)
print(f"已追加到 {file_path}")
smart_append("./logs")
⚡ 快速使用指南
| 需求场景 | 推荐方案 | 一句话说明 |
|---|---|---|
| 给一堆文本文件加版权声明 | Python 脚本 #1 | 支持递归、过滤后缀 |
| 服务器日志追加时间戳 | Shell 脚本 #2 | 一行命令搞定,性能快 |
| Windows 用户 | Batch 脚本 #2 | 双击运行,无需环境 |
| 批量修改 JSON 配置 | Python 脚本 #3 | 自动合并更新键值对 |
| 不同文件追加不同内容 | Python 脚本 #4 | 文件匹配 + 模板追加 |
需要我帮你改写成特定场景的脚本吗?
- 给 CSS/JS 文件追加版本号
- 给 CSV 文件统一添加表头
- 批量插入 SQL 语句到多个 SQL 文件
告诉我你的具体文件类型和要追加的内容,我可以直接给你一个开箱即用的版本!