如何使用python基于大于10kb的文件大小列出目录和子目录中的文件

时间:2014-05-27 09:58:13

标签: python python-2.7

我已经完成了以下方案

  1. 我们可以列出目录中的文件
  2. 我们可以列出文件大小
  3. 的文件

    但是现在我只需要列出文件,只要它们大于某个X KB并且用户提供的输入。

    请帮助一些合适的例子

    这是我的代码

    import os 
    for path, dirs, files in os.walk("PathToDir" ): 
        for f in files: 
            size=os.path.getsize( os.path.join( path, f ) 
            print path, f, size
    

3 个答案:

答案 0 :(得分:1)

这是一个如何走路的例子'通过目录中的文件,然后打印出符合文件大小标准的文件:

注意:如何走路'在这里找到了:

concatenate the directory and file name

# Task: List only files that are greater than some X KB with the input given by the user.


import os

# The directory that we are interested in
myPath = "/users/george/documents/"

# The min size of the file in Bytes
mySize = '10000'

# All the file paths will be stored in this list
filesList= []

for path, subdirs, files in os.walk(myPath):
    for name in files:
        filesList.append(os.path.join(path, name))

for i in filesList:
    # Getting the size in a variable
    fileSize = os.path.getsize(str(i))

    # Print the files that meet the condition
    if int(fileSize) >= int(mySize):
        print "The File: " + str(i) + " is: " + str(fileSize) + " Bytes"

答案 1 :(得分:1)

我使用pathlib模块实现了这一目标。我正在Python 3.7.6上运行Windows

这是代码:


import os 
from pathlib import Path

dir_path = Path('//?/D:/TEST_DIRECTORY')

# IMP_NOTE: If the path is 265 characters long, which exceeds the classic MAX_PATH - 1 (259) character
# limit for DOS paths. Use an extended (verbatim) path such as "\\\\?\\C:\\" in order 
# to access the full length that's supported by the filesystem -- about 32,760 characters. 
# Alternatively, use Windows 10 with Python 3.6+ and enable long DOS paths in the registry.

# pathlib normalizes Windows paths to use backslash, so we can use
# Path('//?/D:/') without having to worry about escaping backslashes.


F_LIST = list(x for x in dir_path.rglob('*.*') if x.is_file() and os.path.getsize(x) >= 10000)

for f in F_LIST:
    print(f.parts[-1] + " ===> " + "Size = " + str(format(os.path.getsize(f), ',d')) + "\n")

# path.parts ==> Provides a tuple giving access to the path’s various components
# (Ref.: pathlib documentation)

希望这会有所帮助! :-)

答案 2 :(得分:0)

limit = raw_input('Enter a file size: ')
if int(limit) > 0:
    import os 
    for path, dirs, files in os.walk("PathToDir" ): 
        for f in files: 
            size=os.path.getsize( os.path.join( path, f ) 
            if size > limit :
                print path, f, size