Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找较大的_文件,但输出意外结果_Python_Centos - Fatal编程技术网

Python 查找较大的_文件,但输出意外结果

Python 查找较大的_文件,但输出意外结果,python,centos,Python,Centos,我有这样一个程序来查找大文件 import os, time, shelve start = time.time() root = '/' # errors= set() # dirs = set() while True: try: root = os.path.abspath(root) #ensure its a abspath #set the baseline as 100M #consider the shift

我有这样一个程序来查找大文件

import os, time, shelve
start = time.time()
root = '/'
# errors= set()
# dirs = set()
while True:
    try:
        root = os.path.abspath(root) #ensure its a abspath
        #set the baseline as 100M 
        #consider the shift
        baseline = 100 * 2**20  # 2*20 is1M
        #setup to collect the large files
        large_files = []

        #root is a better choise as the a concept
        for foldername, subfolders, files in os.walk(root):
            for f in files:
                # print(f"{foldername}, {f}")
                abspath = os.path.join(foldername, f)
                size = os.path.getsize(abspath)
                if size >= baseline:
                    large_files.append((os.path.basename(abspath), size))
                    print(abspath, size/(2**20))

        #write the large files to shelf
        shelf = shelve.open('/root/large_files.db')
        shelf["large_files"] = large_files
        shelf.close()

        if subfolders == []:
            end = time.time()
            break

    except (PermissionError,FileNotFoundError) as e:
        # errors.add(e)
        pass
它始终如一地输出相同的结果

[root@iz2ze9wve43n2nyuvmsfx5z ~]# python3 search_large_files.py 
/dev/core 134217726.0078125
/dev/core 134217726.0078125
/dev/core 134217726.0078125
....
然而,我没有发现任何理由

 print(abspath, size/(2**20))
我会一直这样做


我的代码中可能存在什么问题:

您的
有一个无限的外循环,而True:
,并且显然
/dev/core
是文件系统中唯一一个超过
基线所指定的文件大小的文件,因此它会反复输出相同的文件

删除
而为True:
并取消块内部的缩进,代码将正常工作


请注意,如果子文件夹==[]:
条件超出了os.walk(root)中foldername、子文件夹、文件的
循环,因此将不会有任何用处。无论如何,您都应该无条件地记录结束时间,因此您应该简单地删除
if
条件和
break
语句。

我引入了“while True”,因为如果在MacOS上运行它遇到“PermissionError”,代码将中断。我明白了,但是
while True:
所做的只是再次尝试相同的事情,我认为这对它在第一次迭代中遇到的权限错误没有帮助。您应该找到权限错误的根本原因,避免访问有问题的文件/文件夹,或者允许进程具有访问这些文件/文件夹的适当权限。