0

I am using the following code to loop through multiple subdirectories to append files with .dat extension into a csv but that is not the problem here.

After appending the files into a dataframe i'm trying to create directory and save the file into that directory using os.mkdir() but getting the following error though I'm checking if directory already exists:

    FileExistsError: [WinError 183] Cannot create a file when that file already exists:

    for root,dirs,files in os.walk(r'C:\Users\ngowda\Downloads\DO_driver_logs'):
       for f in files:
        
          print(dirs)
          if f.startswith('DC_autofis_'):
             all_data_autofis = all_data_autofis.append(pd.read_csv(root+'\\'+f,skiprows=1,sep=',',engine='python',skipinitialspace=True))
             dir_ = 'DC_autofis_'
             if not os.path.isdir(dir_):
                path = os.path.join(path_save_files,dir_)
                os.mkdir(path)
             all_data_autofis.to_csv(path+'\\'+'DC_autofis_03.csv')

am i doing something wrong in the code?

nivedan gowda
  • 205
  • 2
  • 9

1 Answers1

1

use if not os.path.exists(directory):

for root,dirs,files in os.walk(r'C:\Users\ngowda\Downloads\DO_driver_logs'):
       for f in files:
        
          print(dirs)
          if f.startswith('DC_autofis_'):
             all_data_autofis = all_data_autofis.append(pd.read_csv(root+'\\'+f,skiprows=1,sep=',',engine='python',skipinitialspace=True))
             dir_ = 'DC_autofis_'
             if not os.path.isdir(dir_):
                path = os.path.join(path_save_files,dir_)
                if not os.path.exists(path ):
                   os.mkdir(path)
             all_data_autofis.to_csv(path+'\\'+'DC_autofis_03.csv')
Jin Thakur
  • 2,711
  • 18
  • 15