簡體   English   中英

Python:如果目錄中有一定數量的文件,則以反向字母順序刪除文件

[英]Python: Deleting files reverse-alphabetically if a certain number of files in in a directory

好吧,刪除日期更短的文件(盡管我相信數字的作用與字母相同)。 例如,我們在一個名為“ BOB”的目錄中包含以下文件:

10-10-2000.txt
11-10-2000.txt
12-10-2000.txt
13-10-2000.txt
14-10-2000.txt

但是我只想要4,所以我需要刪除最近的日期10-10-2000.txt。 但是,這不能僅通過刪除最近創建的文件來完成,因為10-10-2000.txt可能是昨天創建的。

謝謝。

您可以嘗試從文件名創建datetime對象,然后對其進行比較。 我不會為您寫出您的代碼,但是類似:

import datetime as dt
file_names = ... # (maybe try os.listdir()?)
dates = []
for name in file_names:
    dates.append((name, dt.datetime.strptime(x, "%d-%m-%Y.txt")))
# ... logic to sort dates ...
os.remove(dates[0][0]) # if the sort worked, and your first result is the first date

如果您需要有關日期排序的幫助,請問我,但是一旦有了日期,您就應該能夠使用基本的比較運算符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM