user10138366
user10138366

Reputation: 25

Inform when folder is empty in Python?

I am searching for files in a path but some subfolders are empty. Therefore an exception should be used.

If an encounter with an empty folder takes place this error occurs.

FionaValueError: No dataset found at path '/Users\user\Desktop\testn\43003\CBOUND' using drivers: *

So I made an exception for this error:

folder = Path(r"C:\Users\user\Desktop\testn")
shapefiles =glob('/*/*/Desktop/testn/*/*')
#shapefiles =glob('/*/*/Desktop/testm/*/*,recursive = True')

shapefiles
try:
    gdf = pandas.concat([
    geopandas.read_file(shp)
    for shp in shapefiles
    ],sort=True).pipe(geopandas.GeoDataFrame)
    gdf.to_file(folder / 'compiled.shp')
except FionaValueError as ex:
    if shp==[]: #if subfolder is empty print name of folder and subfolder is empty
        print(shp + 'is empty')

and gives

NameError: name 'FionaValueError' is not defined

So what I need is:

1.Print the name of the folder and subfolder that is empty

2.Fix the error that is not recognized in the exception.

Upvotes: 1

Views: 181

Answers (1)

Roelant
Roelant

Reputation: 5119

You should import this error - also see the docs:

from fiona.errors import FionaValueError

To check if a folder is empty you can use a pattern as:

if not os.listdir(path):
    print(f'{path} is empty')

To print the actual empty paths you can rewrite the list comprehension to a standard loop:

from fiona.errors import FionaValueError
import os
import glob
import geopandas as gpd
import pandas as pd 
import path

folder = path.Path(r"C:\Users\user\Desktop\testn")
shapefiles = []
for shpfile in glob.iglob('/*/*/Desktop/testn/*/*'):
    try:
        shapefiles.append(geopandas.read_file(shpfile))
    except FionaValueError as ex:
        if not os.listdir(shpfile):
            print(f'{shpfile} is empty')

gdf = pd.concat(shapefiles, sort=True).pipe(gpd.GeoDataFrame)
gdf.to_file(folder / 'compiled.shp')

Upvotes: 1

Related Questions