python show folder files and not subfolder files

pascal z barpasc at yahoo.com
Wed Sep 23 19:24:32 EDT 2020


Please advise if the following is ok (i don't think it is)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os

csv_contents = ""
output_file = '/home/user/Documents/csv/output3csv.csv'
Lpath = '/home/user/Documents/'

csv_contents = "FOLDER PATH;Size in Byte;Size in Kb;Size in Mb;Size in Gb\n"

d_size = 0
for root, dirs, files in os.walk(Lpath, topdown=False):
    for i in files:
        d_size += os.path.getsize(root + os.sep + i)
    csv_contents += "%s   ;%.2f   ;%.2f   ;%.2f   ;%.2f  \n" % (root, d_size, d_size/1024, d_size/1048576, d_size/1073741824)

    counter = Lpath.count(os.path.sep)
    if counter < 5:
        for f in os.listdir(Lpath):
            path = os.path.join(Lpath, f)
            f_size = 0
            f_size = os.path.getsize(path)
            csv_contents += "%s   ;%.2f   ;%.2f   ;%.2f   ;%.2f  \n" % (path, f_size, f_size/1024, f_size/1048576, f_size/1073741824)

fp = open(output_file, "w")
fp.write(csv_contents)
fp.close()


More information about the Python-list mailing list