python show folder files and not subfolder files

Terry Reedy tjreedy at udel.edu
Thu Sep 24 01:52:28 EDT 2020


On 9/23/2020 7:24 PM, pascal z via Python-list wrote:
> 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()


Read
https://docs.python.org/3/faq/programming.html#what-is-the-most-efficient-way-to-concatenate-many-strings-together
-- 
Terry Jan Reedy



More information about the Python-list mailing list