[Head First Python]4. summary

时间:2023-02-04 05:48:04

1- strip()方法可以从字符串去除不想要的空白符

(role, line_spoken) = each_line.split(":", 1)
line_spoken = line_spoken.strip()

2- print() BIF的file参数控制将数据发送/保存到哪里

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
if indent:
for tab_stop in range(level):
print("\t",end='', file = fn)
print(each_item, file = fn)

3- 会向except组传入一个异常对象,并使用as关键字赋至一个标示符

except IOError as err:
print('file error' + str(err))
except pickle.PickleError as perr:
print('pickle err' + str(perr))

4- str() BIF可以用来访问任何数据对象的串表示

5- locals() BIF返回当然作用域中的变量集合

 try:
data = open ('missing')
print(data.read_line(),end = '')
except IOError as err:
print('file error' + str(err))
finally:
if 'data' in locals():
data.close()
 try:
with open ('missing.txt','w') as data:
print("this is test",file = data)
except IOError as err:
print('file error' + str(err))

6- in 操作符用来检查成员关系

7- + 连接两个字符串

8- with 会自动处理所有已打开文件的关闭工作,即使出现异常也不例外, with也使用as关键字

9- sys.stdout 是python中"标准输出", 可以从标准库的sys模块访问

10- 标准库的pickle模块, 将python数据对象保存到磁盘及从磁盘恢复

11- pickle.dump() 函数将数据保存到磁盘

 try:
with open('man.out', 'wb') as man_out, open('other.out','wb') as other_out:
pickle.dump(man, man_out)
pickle.dump(other, other_out)

12- pickle.load() 函数从磁盘恢复数据

 new_man = []
try:
with open('man.out', 'rb') as man_file:
new_man = pickle.load(man_file)