0

ディレクトリ内のすべてのファイルをリストしようとしてきましたが、そのサブディレクトリ、そのパス、およびPythonでのサイズです。どういうわけか、そのディレクトリ内のファイルのみが表示され、サブディレクトリ内のファイルは表示されません。

import os
from os.path import join, getsize,abspath, isfile

fo=open("Size Listing.txt","a")


def size_list(mypath):
f = []
for (dirpath, dirname, filenames) in os.walk(mypath):
    f.extend(filenames)

for i in f:
    fo.write("\nPath: ")
    fo.write(abspath(i))
    fo.write(" Size: ")
    fo.write(str(getsize(join(mypath,i))))
    fo.write(" bytes")


fo.close()

誰かがここで私を助けてくれますか? また、ソートも行う必要があるため、Pythonでファイルパスとサイズのデータ​​構造を作成する方法を誰でも提案できます。ありがとうございました :)

4

1 に答える 1

0
import os
from os.path import join, getsize

def size_list(mypath):
    with open("PathTest.txt","w") as of:
        for root, dirs, files in os.walk(mypath):
            for f in files:
                fo.write("\nPath: " +  os.path.join(root, f))
                fo.write("\tSize: " +  str(getsize(os.path.join(root, f))) + " bytes")

size_list("path/to/dir")

データ構造の場合、(パス、サイズ)のタプルのリストを次のように使用できます。

def size_list(mypath):
    my_list = []
    with open("PathTest.txt","w") as of:
        for root, dirs, files in os.walk(mypath):
            for f in files:
                my_file = os.path.join(root, f)
                file_size = getsize(my_file)
                my_list.append((my_file, file_size))
                fo.write("\nPath: " +  my_file)
                fo.write("\tSize: " +  str(file_size) + " bytes")
于 2013-06-06T05:17:00.157 に答える