gogo
gogo

Reputation: 63

FileExistsError Errno 17 -- I have no clue why this error is occurring

I have no idea why this error message is coming up... is there something wrong with my file path? Am I using os incorrectly?

any help is much appreciated!

        
        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'

Upvotes: 0

Views: 10668

Answers (1)

richie
richie

Reputation: 181

The exception is thrown from makedirs if the dir you're trying to create already exists. It's ment to notify you of that fact.

You should catch the specific exception like so:

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

Since python 3.4.1 you can use this optional parameter to disable the exception if you dont care whether the dir exists already or not.

os.makedirs(path, exist_ok=True)

Upvotes: 2

Related Questions