之前分享了一期 代码改变生活-文件重命名,最近我写了个爬虫,爬的数据多了,想着要分文件夹来放,就要建文件夹(多个);此外,有些数据不符合我所需,那就要删掉;手工工作量太大,想着用代码来试试。
个人博客:https://blog.csdn.net/zyooooxie
批量建文件夹
需求:创建的文件夹名为 某月份,此文件夹 里面是 (月份+某字母)的子文件夹【26个英文字母】。
def create_folder(self, month, path_abs=None):
if path_abs is not None:
os.chdir(path_abs)
if not os.path.exists(month):
os.mkdir(month)
os.chdir(month)
for i in range(ord("A"), ord("Z")+1):
folder = ''.join([month[-2:], chr(i)])
if not os.path.exists(folder):
os.mkdir(folder)
删除文件
需求:删掉某文件夹种 不到100KB的所有文件
def sort_file_and_delete(self, path_abs):
os.chdir(path_abs)
file = os.listdir(path_abs)
file_list = [f for f in file if os.path.isdir(f) is False]
# sort_file = sorted(file_list, key=lambda x: os.path.getsize(x))
# for s in sort_file:
# print(os.path.getsize(s))
filter_list = list(filter(lambda x: os.path.getsize(x) < 102400, file_list)) # 1KB是 1024B
print(filter_list, '这是要删掉的文件名称list')
for f in filter_list:
os.remove(f)
交流技术 欢迎+QQ 153132336 zy
个人博客 https://blog.csdn.net/zyooooxie