I wrote the below code to be able to iterate through all files, sub-folders and folders given a file path. However, when I run the code it keeps giving me file not found error. It's also worth mentioning that when I run same code on my mac, it was giving me the same error, but I when I set follow_symlink=False the error disappeared.
Could anyone help me with what I'm doing wrong here?
[enter image description here][1]
from pathlib import Path
import csv
import os
import time
from datetime import datetime
class File:
def __init__(self, folder_path):
self.folder_path = Path(folder_path)
def folders(self):
return [folder for folder in self.folder_path.iterdir() if folder.is_dir()]
def summary(self):
errors = []
data_table = []
folders = self.folders()
for folder in folders:
total=0
count = 0
files = folder.glob('**/*')
for file in files :
try:
total+=(os.stat(file, follow_symlinks=False).st_size)
count+=1
except OSError as e:
errors.append(f'Error with file {file} in folder {folder} Error-->{e}')
lm_date = datetime.strftime(datetime.strptime(time.ctime(os.stat(folder).st_mtime),
'%a %b %d %H:%M:%S %Y'), '%d-%b-%Y')
data_table.append({'Path':folder, 'Size in MB':f'{total/1048576}', 'File Count':count,
'Last Modifed Date':lm_date})
lm_date = datetime.strftime(datetime.strptime(time.ctime(os.stat(folder).st_mtime),
'%a %b %d %H:%M:%S %Y'), '%d-%b-%Y')
data_table.append({'Path':folder, 'Size in MB':f'{total/1048576}', 'File Count':count,
'Last Modifed Date':lm_date})
return {'data':data_table, 'error':errors}
def csv_export(self, file_path):
data_list = self.summary()['data']
headers = data_list[0].keys()
with open(file_path, 'w') as fp:
writer = csv.DictWriter(fp, headers)
writer.writeheader()
try:
for data in data_list:
writer.writerow(data)
print(f'file saved to location: {os.path.join(os.getcwd(), file_path)}')
except OSError as e:
print(f'Error exporting data file {e}')
[1]: https://i.stack.imgur.com/0YxQl.jpg Here's the error I'm getting.