作者piligo (霹雳狗)
看板Python
标题筛选掉0kb档案并从list中拔除使用问题
时间Sat Sep 25 04:46:35 2021
透过下方这段来筛选掉0kb的csv档案
csvfilearr=glob.glob(r'*.csv')
dellist=[]
i=1
for item in csvfilearr:
size = os.path.getsize(item)
if size == 0:
dellist+=str(i-1)
i+=1
else:
i+=1
for index in sorted(dellist, reverse=True):
del csvfilearr[int(index)]
这样写10个档案内都没问题,list的 [0,1.....9]
但超过10个档案就出包了,两位数的都会被拆成个位数 [0,1....9,1,0,1,1,1,2]
这要怎麽改写才能变成[0,1....9,10,11,12]
有尝试dellist+=str(i-1)改成dellist+=int(i-1),
但是会报错TypeError: 'int' object is not iterable
谢谢
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 175.181.210.22 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1632516397.A.F86.html
2F:→ chickengod: 用内建的 enumerate() 可以同时得到 index 09/25 05:24
3F:→ chickengod: 我猜 += 左右 type 要一样 所以str 被强制转型成list 09/25 05:37
4F:→ chickengod: 这里要放新元素进list 可以用 list.append() 09/25 05:37
6F:推 s0914714: dellist+=[str(i-1)] 09/25 05:44
7F:推 lycantrope: csvfilearr = [f for f in glob.glob(r"*.csv") 09/25 09:02
8F:→ lycantrope: if os.path.getsize > 0] 09/25 09:03
9F:→ lycantrope: if os.path.getsize(f) > 0] 09/25 09:03
10F:→ piligo: 感谢chickengod s0914714 lycantrope 三个方法都成功 09/26 23:21
11F:→ piligo: 程式也越来越短 短到剩一行 看的真清爽 09/26 23:24