本文目录导读:

Bash 脚本 (Linux/Mac)
创建多个文件
#!/bin/bash
# 循环创建文件
for i in {1..10}; do
touch "file_$i.txt"
done
# 或者创建带前缀的文件
for i in {1..5}; do
echo "这是第 $i 个文件的内容" > "文档_$i.txt"
done
动态生成文件名
#!/bin/bash
# 按日期创建文件
for i in {1..7}; do
filename="$(date +%Y%m%d)_report_$i.txt"
touch "$filename"
done
# 从数组创建
names=("文档" "图片" "数据" "备份")
for name in "${names[@]}"; do
touch "${name}_2024.txt"
done
Python 脚本 (跨平台)
批量创建文件
import os
from pathlib import Path
# 方法1:简单循环
for i in range(1, 11):
filename = f"file_{i}.txt"
with open(filename, 'w') as f:
f.write(f"这是文件 {i} 的内容")
print(f"创建: {filename}")
# 方法2:使用 pathlib
def create_batch_files(path="./files", count=10, prefix="file"):
# 创建目录
Path(path).mkdir(exist_ok=True)
for i in range(1, count+1):
filepath = Path(path) / f"{prefix}_{i}.txt"
filepath.write_text(f"第 {i} 个文件的内容")
print(f"已创建: {filepath}")
# 调用函数
create_batch_files()
PowerShell (Windows)
# 批量创建文件
1..10 | ForEach-Object {
New-Item -Path "file_$_.txt" -ItemType File -Force
Set-Content -Path "file_$_.txt" -Value "这是第 $_ 个文件"
}
# 带目录结构
$folders = @("文档", "图片", "视频")
foreach ($folder in $folders) {
New-Item -Path ".\$folder" -ItemType Directory -Force
1..5 | ForEach-Object {
New-Item -Path ".\$folder\file_$_.txt" -ItemType File -Force
}
}
批量创建多类型文件
#!/bin/bash
# 创建不同类型的文件
for i in {1..5}; do
touch "document_$i.md" # Markdown
touch "script_$i.py" # Python
touch "config_$i.json" # JSON
touch "data_$i.csv" # CSV
done
高级功能示例
Python 高级批量创建
import os
import json
from datetime import datetime
def batch_create_files(config):
"""
根据配置批量创建文件
"""
base_path = config.get('base_path', './')
file_types = config.get('file_types', ['txt'])
count = config.get('count', 10)
prefix = config.get('prefix', 'file')
# 创建目录
if not os.path.exists(base_path):
os.makedirs(base_path)
for i in range(1, count + 1):
for file_type in file_types:
filename = f"{prefix}_{i}.{file_type}"
filepath = os.path.join(base_path, filename)
# 根据类型写入不同内容
if file_type == 'json':
data = {
"id": i,
"name": f"文件{i}",
"created": datetime.now().isoformat()
}
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
else:
with open(filepath, 'w', encoding='utf-8') as f:
f.write(f"这是 {filename} 的内容,创建于 {datetime.now()}")
print(f"已创建: {filepath}")
# 使用示例
config = {
'base_path': './batch_files',
'file_types': ['txt', 'json'],
'count': 5,
'prefix': 'test'
}
batch_create_files(config)
使用方法
- Bash: 保存为
.sh文件,运行bash script.sh - Python: 保存为
.py文件,运行python script.py - PowerShell: 保存为
.ps1文件,在 PowerShell 中运行
小贴士
- 添加检查:防止覆盖已有文件
- 使用变量:便于修改数量、路径等
- 添加日志:记录创建过程
- 错误处理:添加异常捕获
选择哪种方法取决于你的操作系统和具体需求!