Python 可执行到 Linux 列出文件大小

Python executable to Linux list files with sizes

我需要我的 test.py 在 LINUX shell 中显示以下内容 - 列出目录中的所有文件 - 以字节为单位的文件大小的降序(必须显示字节) - 最后显示总文件和总大小(X 文件 X 总大小) - 不包括子目录或其他子目录中的文件

这是我的 python 可执行文件

    #!/usr/bin/env python
    import subprocess
    subprocess.call(["ls", "-l", "-S", "-s"])

这按降序显示了文件及其大小,但它包括 folders/subdirectories 我不想要的

另外将 subprocess.call 替换为 subprocess.call(["find", "-type","f"]) 只显示没有不需要的日期和时间的文件,但我不知道如何获取我想要的信息。

我的python代码:

#!/usr/bin/env python 
import subprocess, os, operator 
directory='e:\Programs/Cyg/home/Dylan/test'       
list=os.listdir(directory) 
pairs=[] 
for file in list:
    if os.path.isfile: 
        location=os.path.join(directory, file)   
        size=os.path.getsize(location) pairs.append((file,size))  
pairs.sort(key=operator.itemgetter(0)) 
for pair in pairs:
   print (pair)

您可以将输出通过管道传递给 grep 以忽略目录。

from subprocess import Popen,PIPE

directory = 'path' 

p1 = Popen(["ls",directory, "-Ssp"], stdout=PIPE)

p2 = Popen(["grep", "-v", '/$'], stdin=p1.stdout, stdout=PIPE)  

p1.stdout.close()
out, _err = p2.communicate()

files = out.splitlines()
total = files.pop(0)
print(total)
print(len(files))

在您自己的代码中,您按错误的键进行排序,您需要将文件大小放在元组中的第一位,以确保实际调用 isfile

import  operator
from os import path, listdir

 directory = 'path' 

lst = listdir(directory)
pairs = []
for f in lst:
    if os.path.isfile(path.join(directory, f)):
        location = path.join(directory, f)
        size = os.path.getsize(location)
        pairs.append((size, f))

pairs.sort(key=operator.itemgetter(0),reverse=True)

print(len(pairs))
print(sum(s for s,_ in pairs))

for size, f in pairs:
    print(size, f)

还需要使用 reverse=True 从高到低排序。如果你想忽略副本,你可以使用 if not f.endswith("~") 或使用 -B 标志和 ls 来忽略备份。要使用 ls 更改文件的输出大小,您需要使用 --block-size 1.

当前目录

from os import listdir
from os.path import isfile, getsize
from operator import itemgetter

files = [(f, getsize(f)) for f in listdir('.') if isfile(f)]
files.sort(key=itemgetter(1), reverse=True)

for f, size in files:
    print '%d %s' % (size, f)
print '(%d files %d total size)' % (len(files), sum(f[1] for f in files))

其他目录

from os import listdir
from operator import itemgetter
from os.path import isfile, getsize, join, basename

def listfiles(dir):
    paths = (join(dir, f) for f in listdir(dir))
    files = [(basename(p), getsize(p)) for p in paths if isfile(p)] 
    files.sort(key=itemgetter(1), reverse=True)

    for f, size in files:
        print '%d %s' % (size, f)
    print '(%d files %d total size)' % (len(files), sum(f[1] for f in files))