Python 函数编写
Shayne Miel
Software Architect @ Duo Security
def copy(src, dst): """Copy the contents of one file to another. Args: src (str): File name of the file to be copied. dst (str): Where to write the new file. """# 打开源文件并读取内容 with open(src) as f_src: contents = f_src.read() # 打开目标文件并写入内容 with open(dst, 'w') as f_dst: f_dst.write(contents)
with open('my_file.txt') as my_file:
for line in my_file:
# 执行操作
def copy(src, dst): """Copy the contents of one file to another. Args: src (str): File name of the file to be copied. dst (str): Where to write the new file. """# 同时打开两个文件 with open(src) as f_src: with open(dst, 'w') as f_dst:# 逐行读写 for line in f_src: f_dst.write(line)
def get_printer(ip): p = connect_to_printer(ip) yield # 必须调用,否则他人将无法连接该打印机 p.disconnect() print('disconnected from printer')doc = {'text': 'This is my text.'} with get_printer('10.0.34.111') as printer: printer.print_page(doc['txt'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
printer.print_page(doc['txt'])
KeyError: 'txt'
try: # 可能出错的代码 except: # 处理错误finally: # 无论如何都会执行
def get_printer(ip): p = connect_to_printer(ip) try: yield finally: p.disconnect() print('disconnected from printer')doc = {'text': 'This is my text.'} with get_printer('10.0.34.111') as printer: printer.print_page(doc['txt'])
disconnected from printer
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
printer.print_page(doc['txt'])
KeyError: 'txt'
| Open | Close |
| Lock | Release |
| Change | Reset |
| Enter | Exit |
| Start | Stop |
| Setup | Teardown |
| Connect | Disconnect |
Python 函数编写