2

I am trying to write a Python script that checks if file exists in a folder if yes, prints file available else skips the steps and checks the next folder. The other additional step I do is if there are any sub-folders within the folder I delete the sub-folder. However, if the folder does not exist the code fails. How could I skip the folder if it does not exist.Given below is the code I am using:

import pandas as pd
import glob
import numpy as np
import os
import os, shutil

path = r'/Users/scott/desktop/sales_data/store1/2018-05-10'
for the_file in os.listdir(path):
    file_path = os.path.join(path, the_file)
        try:
         if os.path.isdir(file_path): shutil.rmtree(file_path)
    except Exception as e:
        print(e)

The error I get is

FileNotFoundError: [Errno 2] No such file or directory: '/Users/scott/desktop/sales_data/store1/2018-05-10'

Could anyone assist. Thanks.

dark horse
  • 3,211
  • 8
  • 19
  • 35
  • I would have a look at this post as well, it seems like it could help you. https://stackoverflow.com/questions/82831/how-to-check-whether-a-file-exists?rq=1 – BLang May 11 '18 at 02:27
  • @BLang thanks for the sharing the link, was helpful to solve my problem – dark horse May 11 '18 at 06:40

1 Answers1

1

This is what I do..would be right above your for loop.

your for loop is actually checking for a path, but you dont check if the path its look for exists.

path = r'/Users/scott/desktop/sales_data/store1/2018-05-10'
if not os.path.isdir(path):
  <do your error code here>
for the_file in os.listdir(path):
   file_path = os.path.join(path, the_file)
       try:
          if os.path.isdir(file_path): shutil.rmtree(file_path)
      except Exception as e:
          print(e)
Sherpa
  • 93
  • 6