选择文件夹中大小最大的文件比在 Python 中应用几个函数要大



我有兴趣在文件夹中查找以kbs为单位的最大文件,然后应用一个函数。之后,我想对同一文件夹中的剩余文件应用不同的功能。如果我知道要使用哪些文件、文件的名称和大小,我将使用以下代码:

with open(big_file, 'r') as bigfile:
   bigfile.rotate #predefined function
   minx, maxx, miny, maxy, minz, maxz = find_mins_maxs(bigfile) #predefined function
   w1 = maxx - minx
   l1 = maxy - miny
   h1 = maxz - minz
   copies = copy_obj(bigfile, (w1, l1, h1), 2, 2, 1)
with open(small_file, 'r') as smallfile:
    minx, maxx, miny, maxy, minz, maxz = find_mins_maxs(smallfile)
    w2 = maxx - minx
    l2 = maxy - miny
    h2 = maxz - minz
    translate(smallfile, w1, w1 / 10., 3, 'x')
    copies2 = copy_obj(smallfile, (w2, l2, h2), 2, 2, 1)
    combined = mesh.Mesh(numpy.concatenate([bigfile.data, smallfile.data] +
                                [copy.data for copy in copies] +
                                [copy.data for copy in copies2]))
    combined.save(folder + '.stl', mode=stl.Mode.ASCII)  # save as ASCII

我如何将其应用于包含许多文件的许多文件夹

这将查找给定目录中最大的文件:

import os
path = '/path/to/directory'
print(max(os.listdir(path), key=lambda x: os.stat(os.path.join(path,x)).st_size))

在 Python 3.5 及更高版本中,您可以执行以下操作:

import os
direntries = list(os.scandir(PATH))
bigfile = max(direntries, key=lambda x: x.stat().st_size)

现在bigfile是一个目录输入对象。然后bigfile.name是文件名,bigfile.path是完整路径。

然后你可以做

dostuff(bigfile)
for f in direntries:
    if f is not bigfile:
       otherstuff(f)

或者,如果要跳过目录:

for f in direntries:
    if f.is_file() and f is not bigfile:
       otherstuff(f)

只需列出您的文件os.listdir,使用 os.path.isfile 检查文件并使用 os.stat 获得更可靠的大小读数,将它们存储在列表中并对列表进行排序:

import os
target = "."  # let's use the current dir as our target
file_list = sorted((os.stat(os.path.join(target, f)).st_size, os.path.join(target, f))
                    for f in os.listdir(target)
                    if os.path.isfile(os.path.join(target, f)))

现在,您的file_list将包含一个元组列表,这些元组(file_size, file_path) target目录中从最小到最大大小排序。

然后你可以使用file_list[-1][1]来获取最大的文件,你可以遍历所有其他文件(file_list[:-1](以对它们执行其他操作,例如:

function_for_the_biggest_file(file_list[-1][1])
for other_file in file_list[:-1]:
    function_for_other_files(other_file[1])

编辑 - 似乎在执行函数后,您希望将它们全部保存在一个文件中,因此:

with open(os.path.join(target, "combined.dat"), "w") as outfile:
    for files in file_list:
        with open(files[1], "r") as f:
            outfile.write(f.read())

这会将combined.dat中的所有文件集中在同一目录中,按文件从小到大的顺序排列。如果要存储从最大文件到最小文件,可以使用for files in reversed(file_list):

最新更新