FileExistsError Errno 17——我不知道为什么会出现这个错误
FileExistsError Errno 17 -- I have no clue why this error is occurring
我不知道为什么会出现此错误消息...我的文件路径有问题吗?我使用 os 不正确吗?
非常感谢任何帮助!
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'
如果您尝试创建的目录已经存在,则 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)
我不知道为什么会出现此错误消息...我的文件路径有问题吗?我使用 os 不正确吗?
非常感谢任何帮助!
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'
如果您尝试创建的目录已经存在,则 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)