【问题标题】:FileExistsError Errno 17 -- I have no clue why this error is occurringFileExistsError Errno 17 -- 我不知道为什么会发生这个错误
【发布时间】:2021-04-30 15:13:32
【问题描述】:

我不知道为什么会出现此错误消息...我的文件路径有问题吗?我是不是用错了操作系统?

非常感谢任何帮助!

        
        def save_hotel_info_file(self):  

                hotel_name = self.name
                new_hotel = (hotel_name.replace(' ', '_')).lower()
      
                path =  'hotels/' + hotel_name
        
                os.makedirs(path)
        
                fobj = open('hotel_info.txt', 'w', encoding='utf-8')
        
                fobj.write(self.name + '\n')
        
                for room_obj in self.rooms:
                    room_str = 'Room ' + str(room_obj.room_num) + ',' + room_obj.room_type + ',' + str(room_obj.price)
                    fobj.write(room_str + '\n')

                fobj.close()
    ```

Traceback (most recent call last):
  File "/Users/myname/Documents/hotel.py", line 136, in <module>
    h.save_hotel_info_file()
  File "/Users/myname/Documents/hotel.py", line 120, in save_hotel_info_file
    os.makedirs(path)
  File "/Applications/Thonny.app/Contents/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/../../../../../../../Python.framework/Versions/3.7/lib/python3.7/os.py", line 223, in makedirs
    mkdir(name, mode)
FileExistsError: [Errno 17] File exists: 'hotels/Queen Elizabeth Hotel'

【问题讨论】:

    标签: python file-io


    【解决方案1】:

    如果您尝试创建的目录已经存在,则 mkdirs 会引发异常。通知您这一事实。

    您应该像这样捕获特定异常:

    try:
        os.makedirs(path)
    except FileExistsError:
        # the dir already exists
        # put code handing this case here
        pass
    

    从 python 3.4.1 开始,如果你不关心目录是否已经存在,你可以使用这个可选参数来禁用异常。

    os.makedirs(path, exist_ok=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      相关资源
      最近更新 更多