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

4

你好,我正在使用一个小脚本。我试图打印出当前目录中的所有文件,并将文件名:文件大小作为键:值对存储到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}

任何帮助都是可贵的。


size_limit 不应该是 argv[2] 吗?我认为 argv[0] 是命令本身,然后 argv[1] 是第一个参数。 - ASCIIThenANSI
应该是argv [1],我使用print来检查它。第一个“python”用于运行Python程序。 - user5691801
问题似乎在于您的if语句没有正确检查大小是否在限制范围之内。 - ASCIIThenANSI
4个回答

6

我为您提供了尽可能简洁的代码:

这个程序:

  1. Is dynamic, and will work in any directory you put it in.
  2. Can convert sizes to MB and KB very easily in the Calculating for-loop.
  3. Only imports 1 library.
  4. Ends with a dict of all stat info organized by ['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

1
将您的大小限制转换为 int
size_limit = int(argv[1])

0

名称:

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

大小(假设您已经有了“nameList”:

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

0
当你从命令行参数中读取size_limit时,它被读取为字符串,而不是整数。然后在以下代码行中将数字与字符串进行比较:
if os.path.getsize(my_path+item) < size_limit:
    ...

在Python 2.x中,当你将数字类型与非数字类型进行比较时,数字类型始终小于比较中的其他类型,因此上面的代码行将始终返回true。在Python 3.x中,您的比较将引发TypeError

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

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

# Here I convert the argument you get to an integer
size_limit = int(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)

1
在Python 3.x中,使用<比较字符串和整数将会引发异常。 - Karl Knechtel
@KarlKnechtel 谢谢 - 我对 Python 3.x 的行为不太熟悉,但我已经更新了我的帖子,以便更加清晰明了。 - wkl
1
@KarlKnechtel 哦,我明白为什么我没有感觉了... 我的Python之旅从Python 3开始... 谢谢你告诉我。 - user5691801

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接