python show .

pascal z barpasc at yahoo.com
Wed Sep 23 16:24:03 EDT 2020


Hello, I'm working on a script where I want to loop into folders somehow recursively to get information but I want to limit the infos for the files on a certain level of folders for example:

/home/user/Documents/folder1
/home/user/Documents/folder2
/home/user/Documents/folder3/folder1/file1
/home/user/Documents/folder4/file1
/home/user/Documents/file1
/home/user/Documents/file2
/home/user/Documents/file3

I only want file1, 2, 3 at the root of Documents to show (write to a csv) and I'm using the script below

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

import os

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

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

for root, dirs, files in os.walk(Lpath, topdown=False):
    counter = Lpath.count(os.path.sep)
    if counter < 5:
        for f in os.listdir(root):
            path = os.path.join(root, 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()
### END OF SCRIPT###

When I run this script, I get files in subfolders. For now, I need to keep using "os.walk" because the script includes functions that I didn't include to make thing simple.

Pascal


More information about the Python-list mailing list