(3分)遍历/data/resources/下的文件,找出大于200M的文件,判断其若以“tar”结尾,则使用rm删除;若以“log“结尾,则清空该文件。
时间: 2024-01-14 13:02:46 浏览: 27
以下是实现该功能的Python代码:
```python
import os
directory = "/data/resources/"
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
if os.path.isfile(filepath) and os.path.getsize(filepath) > 200 * 1024 * 1024:
if filename.endswith(".tar"):
os.remove(filepath)
elif filename.endswith(".log"):
with open(filepath, "w"):
pass
```
该代码首先遍历指定目录下的所有文件,如果文件大小大于200M,则根据文件名的后缀执行不同的操作。如果以“.tar”结尾,则使用os模块的remove()函数删除该文件;如果以“.log”结尾,则使用Python的with语句打开该文件并清空其内容。需要注意的是,文件大小的单位是字节,因此需要将200M转换为字节数。