实用脚本代码:批量处理文件、图片和文本
以下是一些实用的脚本代码:
- 批量修改文件名
import os
path = '/path/to/files/'
for filename in os.listdir(path):
# 修改文件名的逻辑
new_filename = filename.replace('old', 'new')
os.rename(os.path.join(path, filename), os.path.join(path, new_filename))
- 批量转换图片格式
from PIL import Image
import os
path = '/path/to/images/'
for filename in os.listdir(path):
if filename.endswith('.jpg'):
# 转换图片格式的逻辑
img = Image.open(os.path.join(path, filename))
new_filename = filename.replace('.jpg', '.png')
img.save(os.path.join(path, new_filename))
- 批量压缩图片大小
from PIL import Image
import os
path = '/path/to/images/'
for filename in os.listdir(path):
if filename.endswith('.jpg') or filename.endswith('.png'):
# 压缩图片大小的逻辑
img = Image.open(os.path.join(path, filename))
img = img.resize((800, 600))
img.save(os.path.join(path, filename))
- 批量转换文本编码格式
import os
path = '/path/to/files/'
for filename in os.listdir(path):
if filename.endswith('.txt'):
# 转换文本编码格式的逻辑
with open(os.path.join(path, filename), 'r', encoding='utf-8') as f:
content = f.read()
with open(os.path.join(path, filename), 'w', encoding='gbk') as f:
f.write(content)
- 批量替换文本内容
import os
path = '/path/to/files/'
for filename in os.listdir(path):
if filename.endswith('.txt'):
# 替换文本内容的逻辑
with open(os.path.join(path, filename), 'r', encoding='utf-8') as f:
content = f.read()
new_content = content.replace('old', 'new')
with open(os.path.join(path, filename), 'w', encoding='utf-8') as f:
f.write(new_content)
原文地址: http://www.cveoy.top/t/topic/okgE 著作权归作者所有。请勿转载和采集!