Skip to main content
 首页 » 编程设计

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

2024年10月24日9Leo_wl

您好,我正在使用一个小脚本。我尝试打印当前目录中的所有文件,并将 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} 

感谢任何帮助。

请您参考如下方法:

这是我用我能想到的最少行数为您提供的:

这个程序:

  1. 是动态的,可以在您放入的任何目录中工作。
  2. 可以在计算 for 循环中非常轻松地将大小转换为 MB 和 KB。
  3. 仅导入 1 个库。
  4. 以 ['Filename'] 组织的所有统计信息的字典结束: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)) 
    

示例输出:

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