【发布时间】:2015-05-14 15:17:23
【问题描述】:
我需要帮助计算 python 中的目录/文件夹 (Windows 7) 中的文件数量,所以如果有超过 20 个 .txt 文件,我可以删除一些,总有 20 个 .txt 文件。如果您使用 python 创建另一个,它会删除最旧的。
任何答案都会有所帮助,谢谢。
import os
(_, _, my_files) = os.walk("C:\\Users\\guest.user\\task2").next()
amount = len([f for f in my_files if f.endswith('.txt')])
print amount
if amount > 20:
#This is my next problem - needs to truncate the file once there is more than 20
【问题讨论】:
-
你能粘贴一些你到目前为止尝试过的代码吗?
-
当您显然对子目录不感兴趣时,为什么还要使用 os.walk? os.listdir 为您提供一个目录中的所有文件。 glob.glob 甚至可以让你指定一个模式,比如 glob.glob('*.txt')。
标签: python python-2.7 variables counting