使用时出现错误2手术室步行在Python中

2024-04-19 13:34:57 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个脚本,用于搜索大于指定大小的文件:

def size_scan(folder, size=100000000):
    """Scan folder for files bigger than specified size

    folder: abspath
    size: size in bytes
    """
    flag = False

    for folder, subfolders, files in os.walk(folder):
        # skip 'anaconda3' folder
        if 'anaconda3' in folder:
            continue

        for file in files: 
            file_path = os.path.join(folder, file)
            if os.path.getsize(file_path) > size:
                print(file_path, ':', os.path.getsize(file_path))
                flag = True

    if not flag:
        print('There is nothing, Cleric')

我在Linux中扫描根文件夹时收到以下错误消息:

^{pr2}$

我猜是因为Python解释器不能扫描自己,所以我试图从搜索中跳过'anaconda3'文件夹(在上面的代码中用#skip anaconda文件夹标记)。但是,错误消息保持不变。

谁能解释一下吗?

(如果这类问题在这里是不允许的,应该编辑的,请告诉我。谢谢)


Tags: pathin文件夹forsizeifosfiles
1条回答
网友
1楼 · 发布于 2024-04-19 13:34:57

python试图获取的文件大小与os.stat(filename).st_size是一个断开的链接。断开的链接是指其目标已被移除的链接。它很像一个互联网链接,给出一个404。若要在脚本中修复此问题,请检查该文件是否为文件(首选),或使用try/catch(非首选)。若要检查该文件是否是文件而不是断开的链接,请使用^{}。您的代码应该如下所示:

def size_scan(folder, size=100000000):
"""Scan folder for files bigger than specified size

folder: abspath
size: size in bytes
"""
flag = False

for folder, subfolders, files in os.walk(folder):
    # skip 'anaconda3' folder
    if 'anaconda3' in folder:
        continue

    for file in files: 
        file_path = os.path.join(folder, file)
        if os.path.isfile(file_path) and (os.path.getsize(file_path) > size):
            print(file_path, ':', os.path.getsize(file_path))
            flag = True

if not flag:
    print('There is nothing, Cleric')

因此,在获取大小之前,它会检查文件是否真的存在,跟踪所有链接以确保它存在。Related SO post。在

相关问题 更多 >