文件读写追加: f = open(‘文件路径\名称\格式’,mode=(r/w/a),encoding = ‘UTF-8’) file = f.read/write() print(file) or with open(‘文件路径\名称\格式’,‘r/w/a’,encoding = ‘UTF-8’) as f: file = f.read/write() print(file) 文件异常:try - except: try: 检测范围 except Exception(as reason): 出现异常(Exception)后处理的代码 while True: try: x = int(input("请输入一个数字: ")) break except ValueError: print(“您输入的不是数字,请再次尝试输入!”) except子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组:except (RuntimeError, TypeError, NameError):
import sys
```python
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
```python
try:
f = open('stu.txt','r',encoding='utf-8')
print(f.read())
f.close()
except OSError:
print('文件错了!')
try/except...else:
import sys
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
try - finally:
try:
runoob()
except AssertionError as error:
print(error)
else:
try:
with open('file.log') as file:
read_data = file.read()
except FileNotFoundError as fnf_error:
print(fnf_error)
finally:
print('这句话,无论异常是否发生都会执行。')
raise()语句:raise [Exception [, args [, traceback]]];(让代码报错,触发异常)
x = 20
if x > 15:
raise Exception('x 不能大于 15。x 的值为: {}'.format(x))
输出异常:#Traceback (most recent call last):
File "test.py", line 3, in <module>
raise Exception('x 不能大于 15。x 的值为: {}'.format(x))
Exception: x 不能大于 15。x 的值为: 20
|