篩選掉0kb檔案並從list中拔除使用問題

看板Python作者 (霹靂狗)時間3年前 (2021/09/25 04:46), 編輯推噓2(209)
留言11則, 4人參與, 3年前最新討論串1/1
透過下方這段來篩選掉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://www.ptt.cc/bbs/Python/M.1632516397.A.F86.html

09/25 05:24, 3年前 , 1F

09/25 05:24, 3年前 , 2F
用內建的 enumerate() 可以同時得到 index
09/25 05:24, 2F

09/25 05:37, 3年前 , 3F
我猜 += 左右 type 要一樣 所以str 被強制轉型成list
09/25 05:37, 3F

09/25 05:37, 3年前 , 4F
這裡要放新元素進list 可以用 list.append()
09/25 05:37, 4F

09/25 05:42, 3年前 , 5F

09/25 05:44, 3年前 , 6F
dellist+=[str(i-1)]
09/25 05:44, 6F

09/25 09:02, 3年前 , 7F
csvfilearr = [f for f in glob.glob(r"*.csv")
09/25 09:02, 7F

09/25 09:03, 3年前 , 8F
if os.path.getsize > 0]
09/25 09:03, 8F

09/25 09:03, 3年前 , 9F
if os.path.getsize(f) > 0]
09/25 09:03, 9F

09/26 23:21, 3年前 , 10F
感謝chickengod s0914714 lycantrope 三個方法都成功
09/26 23:21, 10F

09/26 23:24, 3年前 , 11F
程式也越來越短 短到剩一行 看的真清爽
09/26 23:24, 11F
文章代碼(AID): #1XJZaj-6 (Python)
文章代碼(AID): #1XJZaj-6 (Python)