【问题标题】:python FileExistsError: [WinError 183] Cannot create a file when that file already exists: [duplicate]python FileExistsError:[WinError 183]当文件已经存在时无法创建文件:[重复]
【发布时间】:2021-09-29 20:48:36
【问题描述】:

我正在使用以下代码循环访问多个子目录,以将扩展名为 .dat 的文件附加到 csv 中,但这不是问题所在。

将文件附加到数据框后,我尝试使用 os.mkdir() 创建目录并将文件保存到该目录中,但在检查目录是否已存在时出现以下错误:

    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')

我在代码中做错了吗?

【问题讨论】:

    标签: python


    【解决方案1】:

    使用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')
    

    【讨论】:

      猜你喜欢
      • 2018-02-14
      • 2022-07-06
      • 2022-12-16
      • 2020-04-12
      • 2019-06-26
      • 2021-11-19
      • 2017-07-29
      • 2012-11-12
      相关资源
      最近更新 更多