Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

python - Get files from Directory Argument, Sorting by Size

I'm trying to write a program that takes a command line argument, scans through the directory tree provided by the argument and creating a list of every file in the directory, and then sorting by length of files.

I'm not much of a script-guy - but this is what I've got and it's not working:

import sys
import os
from os.path import getsize

file_list = []

#Get dirpath
dirpath = os.path.abspath(sys.argv[0])
if os.path.isdir(dirpath):
    #Get all entries in the directory
    for root, dirs, files in os.walk(dirpath):
        for name in files:
            file_list.append(name)
        file_list = sorted(file_list, key=getsize)
        for item in file_list:
            sys.stdout.write(str(file) + '
')

else:
    print "not found"

Can anyone point me in the right direction?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a approach using generators. Should be faster for large number of files…

This is the beginning of both examples:

import os, operator, sys
dirpath = os.path.abspath(sys.argv[0])
# make a generator for all file paths within dirpath
all_files = ( os.path.join(basedir, filename) for basedir, dirs, files in os.walk(dirpath) for filename in files   )

If you just want a list of the files without the size, you can use this:

sorted_files = sorted(all_files, key = os.path.getsize)

But if you want files and paths in a list, you can use this:

# make a generator for tuples of file path and size: ('/Path/to/the.file', 1024)
files_and_sizes = ( (path, os.path.getsize(path)) for path in all_files )
sorted_files_with_size = sorted( files_and_sizes, key = operator.itemgetter(1) )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...