如何在Python中获取当前目录中的所有文件名和文件大小

时间:2015-12-17 16:21:51

标签: python

您好我正在使用一个小脚本。我尝试打印当前目录中的所有文件,并将filename:filesize key:value对存储到size_dir

from os import listdir,environ
from sys import argv
from os.path import isfile,join
import os

size_limit = argv[1]
my_path = "./"
onlyfiles = [f for f in listdir(my_path) if isfile(join(my_path, f))]
sizes = []
size_dir = {}
print size_limit
for item in onlyfiles:
    print type(os.path.getsize(my_path+item))
    if os.path.getsize(my_path+item) < size_limit:
        size_dir[item] = os.path.getsize(my_path+item)
print(size_dir)

我在终端上运行这个程序:

python THISFILENAME.py 300

正如我所料,size_limit从我的输入命令收到了300。在for循环中,我设置了一个if语句来检查文件是否超过size_limit,如果没有,那么我们将文件添加到size_dir。 但是,当我打印size_dir时,我发现size_dir包含当前目录中的每个文件,这不是我所期望的。

结果:

{'dir_print.py': 825, 'argvdemo.py': 215, 'formatter.py': 404}

感谢任何帮助。

4 个答案:

答案 0 :(得分:1)

将尺寸限制转换为int

size_limit = int(argv[1])

答案 1 :(得分:1)

以下是我能想到的线路最少的部分:

这个程序:

  1. 是动态的,可以在您放入的任何目录中使用。
  2. 可以在Calculating for-loop中非常轻松地将大小转换为MB和KB。
  3. 仅导入1个库。
  4. 以['Filename']组织的所有统计信息的dict结束:stats

    import os
    thePath = os.getcwd()
    theFiles = list(os.listdir(thePath))
    
    theDict = dict()
    for something in theFiles: #Calculate size for all files here. 
        theStats = os.stat(something)
        theDict[something] = theStats
    
    for item in theDict:
        print("The File: {:30s} The Size: {:d} Bytes".format(item,theDict[item].st_size))
    
  5. 示例输出:

    The File: .idea                          The Size: 272 Bytes
    The File: getFileSizes.py                The Size: 319 Bytes
    The File: testMissingItems.txt           The Size: 201 Bytes
    The File: testVariablesFromMethods.py    The Size: 1372 Bytes
    The File: .DS_Store                      The Size: 6148 Bytes
    The File: detectSpace.py                 The Size: 1180 Bytes
    

答案 2 :(得分:0)

名称:

import os
nameList = os.listdir("path")

大小(假设您已经拥有&#34; nameList&#34;:

statinfo = os.stat(nameList[index])
fileSize = statinfo.st_size

答案 3 :(得分:0)

当您从命令行参数中读取$arr = ['rooms/creative/thelastofus=1' ,'rooms/fantasy/americangods=1' ,'rooms/fantasy/arvandor=1' ,'rooms/creative/thetombs=1' ,'rooms/creative/varekai=1' ,'rooms/erotic/denofdecadence=1' ,'rooms/erotic/dungeon=1' ,'rooms/gorean/aldushara=1' ,'rooms/gorean/grpexplorations=1' ]; print_r($arr); uasort($arr, function($a,$b){ $splitA = explode('/',$a); $splitB = explode('/',$b); if( $splitA[1] == $splitB[1] ){ //Compare filenames if( $splitA[2] == $splitB[2] ){ return 0; } else{ return $splitA[2] < $splitB[2] ? -1 : 1; } } else{ return $splitA[1] < $splitB[1] ? -1 : 1; } }); print_r($arr); 时,它将被读取为字符串,而不是整数。然后,您将数字与行中的字符串进行比较:

size_limit

在Python 2.x中将数值类型与非数字类型进行比较时,数字类型总是小于比较中的其他类型,因此上面的行将始终返回true 。在Python 3.x中,您的比较会引发if os.path.getsize(my_path+item) < size_limit: ...

您应该将TypeError转换为整数以使其正常工作(请注意分配size_limit的行。)

size_limit