简体   繁体   English

Python无限循环同时确定文件大小

[英]Python infinite loop while determining the file size

I'm ending up with an infinite loop while trying to determine the size of the folders in the drive. 在尝试确定驱动器中文件夹的大小时,我最终会遇到无限循环。 Here is the code I'm using, 这是我正在使用的代码,

import os
from os.path import join, getsize
from sys import exit

filepath="P:\\GIS\\Data"

dirList=os.listdir(filepath)

for fname in dirList:   
    for root, dir, files in os.walk(filepath):

        print  root , sum([getsize(join(root, name)) for name in files]),
        print  "bytes in", len(files), "non-directory files"


print "All finished!"

I have tried saving the result in a variable but loop does not even reach to that step and starts looping infinitely Please could you advise me where it is going wrong? 我已经尝试将结果保存在变量中,但循环甚至没有达到该步骤并开始无限循环请你能告诉我哪里出错了吗?

filepath="P:\\GIS\\Data"

dirList=os.listdir(filepath)

for fname in dirList:   
    for root, dir, files in os.walk(filepath):

You want to walk through every directory tree inside "P:\\\\GIS\\\\Data" and that's what you do in your second loop. 您想要遍历"P:\\\\GIS\\\\Data"中的每个目录树,这就是您在第二个循环中所做的事情。 However, you're doing this for every directory inside this directory because you iterate over dirList first, and you aren't even using fname . 但是,您正在为此目录中的每个目录执行此操作因为您首先迭代dirList ,而您甚至不使用fname

Thus, for every directory in dirList , you do the same print s all over again, which gives you the wrong impression of an infinite loop. 因此,对于dirList每个目录,您将再次执行相同的print ,这会给您带来无限循环的错误印象。

Try removing for fname in dirList: and your script should reach its end. 尝试for fname in dirList:删除for fname in dirList:并且您的脚本应该到达它的结尾。

It's unlikely to be an infinite loop or recursion because of os.walk because 由于os.walk,它不太可能是无限循环或递归

By default, walk() will not walk down into symbolic links that resolve to directories. 默认情况下,walk()不会向下走到解析为目录的符号链接。 Set followlinks to True to visit directories pointed to by symlinks, on systems that support them. 将followlinks设置为True以访问符号链接指向的目录,在支持它们的系统上。

But you do have a nested loop and this probably creates the impression that your code is infinite looping. 但是你确实有一个嵌套循环,这可能会造成你的代码无限循环的印象。

You could simplify this to avoid the nested loop 您可以简化此操作以避免嵌套循环

for root, dir, files in os.walk("P:\\GIS\\Data"):

    print  root , sum([getsize(join(root, name)) for name in files]),
    print  "bytes in", len(files), "non-directory files"

this I believe will produce the desired result. 我相信这会产生预期的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM