【问题标题】:Counting files and incrementing variable Python计数文件和递增变量 Python
【发布时间】:2013-05-27 17:18:37
【问题描述】:

尝试遍历驱动器上的每个文件夹,计算每个文件夹中的文件数,如果文件数大于或等于 3,则增加计数。应该很容易吧?好吧,我已经完全搞砸了,我很茫然。

import os, os.path, sys

rootdir = 'q:'

documentedcount = 0

for root, subFolders, files in os.walk(rootdir):
    filecount = len([name for name in os.listdir('.') if os.path.isfile(name)])
    print "Filecount = %s" % filecount
    if  filecount >= 3:
        documentedcount =+1
        print "Documented in the loop is %s" % documentedcount

print "Documented = %s" % documentedcount

它不想超出根目录并进入任何子文件夹。这让我发疯了,因为这应该很简单,但我似乎无法理解它。

【问题讨论】:

  • 请更正缩进以匹配您的实际实现——这很重要。

标签: python for-loop syntax directory


【解决方案1】:

好吧,os.walk() 不会在每次迭代时更改工作目录,所以行...

filecount = len([name for name in os.listdir('.') if os.path.isfile(name)])

...当您启动脚本时,将始终计算当前工作目录中的文件数。

但是,有一个更简单的方法,因为 os.walk() 返回的每个元组中的第三项已经为您提供了目录中所有(非目录)文件的列表,因此您可以使用 len(files).. .

import os, os.path, sys

rootdir = 'q:'

documentedcount = 0

for root, subFolders, files in os.walk(rootdir):
    filecount = len(files)
    print "Filecount = %s" % filecount
    if filecount >= 3:
        documentedcount =+1
        print "Documented in the loop is %s" % documentedcount

print "Documented = %s" % documentedcount

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 2023-02-19
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 2017-06-27
    • 1970-01-01
    相关资源
    最近更新 更多