最近在写python中,发现try else一直报错,查文档都说是字符格式错误,找了一两个小时也没发现哪里格式错误,最后经过实践发现是语法格式错误,在python3.7中,必须先写try,再写except,最后才能写else。一定不能把else直接放到try后面,否则会报语法错误。
try:
print(file_name)
f = open("/admin"+file_name,'rb')
except:
response = 'HTTP/1.1 200 OK\r\n'
response += '\r\n'
response += '------------- file not found ---------'
new_scoket.send(response.encode('utf-8'))
else:
html_content = f.read()
f.close()
# 加\r\n两个,是由于windows与linuex系统里面的转义字符不一样造成的
response = 'HTTP/1.1 200 OK\r\n'
response += '\r\n'
# 把response header发送回去
new_scoket.send(response.encode('utf-8'))
# 把response body发送出去
new_scoket.send(html_content)
print("返回的数据", response)
print("返回的body", html_content)
print("*" * 100)