python - 如何使用 Python 按大小搜索文件

标签 python linux

<分区>

我卡住了。我需要使用 Python 编写代码来按大小查找文件并将其名称和大小添加到列表中。我有一个按名称在目录中搜索文件的程序。我需要使用 get opt 制作另一个标志以按大小进行搜索。

import getopt
import sys
import os
from os import listdir, walk
from os.path import isfile, join

def find_by_name(name, path, result): #Define a function to search the file by it's name
    result = []
    for root, dirs, files in os.walk(path):
        if name in files:
            result.append(os.path.join(name)) #Join the file to the list called result
        else:
            print ("Nothing was found by %s" % name)
        return result
def main():
    path_dir = raw_input("Select the directory you want to search: ")
    results = []
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'n:y:d:')
    except getopt.GetoptError as err:
        print (err)
        sys.exit

    for o, a in opts:
        if o in ("-n", "--name"):
           pro = find_by_name(a, path_dir, results)
if __name__ == "__main__":
    main()

最佳答案

os.walk 为您提供路径和文件名。然后你可以使用

stats = os.stat(path+name)
stats.st_size

以字节为单位获取文件大小。所以你可以把你当前的功能改成这样:

def find_by_size(size, path):
    result = []
    for root, dirs, files in os.walk(path):
        if os.stat(path+name).st_size == size:
            result.append((os.path.join(name), stats.st_size))
        else:
            print ("Nothing of size %d was found" % size)
        return result

您也不需要传递结果,因为您只是用一个空列表替换它。 Python 可以从函数返回列表。

关于python - 如何使用 Python 按大小搜索文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23689419/

相关文章:

python - 从分类数据类型列中提取平均值

linux - 为什么在这种情况下会发生优先级反转 - Linux?

ruby - 顶级程序从 ruby​​ 返回的值少于 linux 上的 bash

linux - 如何在 shell 脚本中为结果集附加一列

python - 如何让 mock.mock_open 引发 IOError?

python - 在 Python 3 中绘制罂粟花

python - 使用 pandas 在多列中应用 IF 条件

python - 如何加速 Ising 模型的 MC 模拟?

linux - 如何使用不同的文件名在不同的 shell 脚本文件中记录 stdout 和 stderr

c - 从内部捕获 SIGSEGV 时,如何知道涉及的无效访问类型?