相关文章推荐
有胆有识的小狗  ·  Swift withUnsafeBytes ...·  4 月前    · 
不拘小节的小蝌蚪  ·  Qt 焦点窗口_qt ...·  1 年前    · 
踏实的墨镜  ·  调用 SSPI ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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'

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

You should catch the specific exception like so:

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

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

os.makedirs(path, exist_ok=True)
                I am trying to make a folder with the same name as a file with makedirs with exist_ok and it still throws the exception!
– John Glen
                Apr 3, 2022 at 1:27
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.