Python 批处理数据
时间: 2023-07-15 17:14:51 浏览: 45
Python 可以用于批处理数据,实现自动化的数据处理,以下是一个简单的示例:
1. 批量重命名文件
```python
import os
# 获取目录下所有文件
files = os.listdir('path/to/folder')
# 遍历文件并重命名
for i, file in enumerate(files):
os.rename(os.path.join('path/to/folder', file), os.path.join('path/to/folder', f'new_name_{i}.jpg'))
```
2. 批量处理 CSV 文件
```python
import pandas as pd
# 读取 CSV 文件
df = pd.read_csv('path/to/file.csv')
# 处理数据
df['new_column'] = df['old_column'].apply(lambda x: x * 2)
# 输出到新文件
df.to_csv('path/to/new_file.csv', index=False)
```
3. 批量压缩文件
```python
import zipfile
# 获取目录下所有文件
files = os.listdir('path/to/folder')
# 创建压缩包
with zipfile.ZipFile('path/to/new_zip.zip', 'w') as zip:
# 遍历文件并压缩
for file in files:
zip.write(os.path.join('path/to/folder', file), file)
```
以上是批处理数据的三个示例,可以根据具体需求进行修改和扩展。