繁体   English   中英

在Python中使用os.walk时出现Errno 2

[英]Errno 2 while using os.walk in 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中扫描根文件夹时收到以下错误消息:

Traceback (most recent call last):

  File "<ipython-input-123-d2865b8a190c>", line 1, in <module>
    runfile('/home/ozramsay/Code/sizescan.py', wdir='/home/ozramsay/Code')

  File "/home/ozramsay/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "/home/ozramsay/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/home/ozramsay/Code/sizescan.py", line 32, in <module>
    size_scan('/')

  File "/home/ozramsay/Code/sizescan.py", line 25, in size_scan
    if os.path.getsize(file_path) > size:

  File "/home/ozramsay/anaconda3/lib/python3.6/genericpath.py", line 50, in getsize
    return os.stat(filename).st_size

FileNotFoundError: [Errno 2] No such file or directory: '/run/udev/link.dvdrw'

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

谁能解释一下?

(请让我知道是否在这里不允许此类问题,应予以编辑。谢谢)

python尝试使用os.stat(filename).st_size获取文件的大小os.stat(filename).st_size是断开的链接。 断开的链接是已删除其目标的链接。 它很像提供404的Internet链接。要在脚本中解决此问题,请检查它是否是文件(首选),或使用try / catch(首选)。 要检查文件是否是文件而不是断开的链接,请使用os.path.isfile(file_path) 您的代码应如下所示:

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')

因此,在获取大小之前,它将检查所有链接是否存在,以确保文件确实存在。 相关的SO帖子

暂无
暂无

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

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