python - 输出是一列数字而不是一个总数

标签 python python-3.x

我对编程非常陌生,我正在尝试做一些可能非常简单的事情。我似乎无法找到正确的线程,尽管在这里向我展示我正在尝试做什么,或者也许我正在搜索错误的线程。

我正在尝试遍历一个目录,并在此过程中计算我要删除或移动的不同类型项目的数量,并让它打印出单个总金额,而不是一一计数到最终数量。

    def files_to_be_moved():
        count = 0
        for (dirname, dirs, files) in os.walk(directory):
            for filename in files:
                if filename.endswith(extensions_to_move):
                    count = count + 1
                    print(count, 'files have been moved')
                    #shutil.move(directory)

我希望看到这样的打印结果:“237 个文件已被移动”,但我得到的是“1 个文件已被移动”、“2 个文件已被移动”...等,直到到达末尾。

最佳答案

只需更改该行,使其位于循环之外:

def files_to_be_moved():
    count = 0
    for (dirname, dirs, files) in os.walk(directory):
        for filename in files:
            if filename.endswith(extensions_to_move):
                count = count + 1
    print(count, 'files have been moved')
    # ^^^

关于python - 输出是一列数字而不是一个总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57045295/

相关文章:

python - scrapy蜘蛛: output in chronological order

python - 如何使用 OpenCV 在 Python 中将单个 BGR 数组转换为 HSV 数组?

python - 专门处理文件存在异常

python - 将值列表添加到现有字典列表(性能关键)

python - docker-compose “/usr/local/bin/python: error while loading shared libraries: libpython3.8.so.1.0: ”时出错

python - 加速 pandas 上的复杂功能

Python Statsmodel ARIMA 启动 [平稳性]

python - 添加多线程或异步到网络抓取

python-3.x - 为什么这在我的request.get变量上显示为语法错误?

python - __next__ 在生成器和迭代器中,什么是方法包装器?