栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用open with语句打开文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用open with语句打开文件

Python允许将多个

open()
语句放在一个语句中
with
。您用逗号分隔。您的代码将是:

def filter(txt, oldfile, newfile):    '''    Read a list of names from a file line by line into an output file.    If a line begins with a particular name, insert a string of text    after the name before appending the line to the output file.    '''    with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:        for line in infile: if line.startswith(txt):     line = line[0:len(txt)] + ' - Truly a great person!n' outfile.write(line)# input the name you want to check againsttext = input('Please enter the name of a great person: ')    letsgo = filter(text,'Spanish', 'Spanish2')

不,通过

return
在函数的末尾放置一个显式字符不会获得任何收益。您可以使用
return
提前退出,但最后要退出,并且该函数将在没有退出的情况下退出。(当然,对于返回值的函数,您可以使用
return
来指定要返回的值。)

引入该语句时,Python 2.5或Python 2.6不支持

open()
与一起使用多个项目,但Python 2.7和Python
3.1或更高版本
with
支持使用多个项目
with

http://docs.python.org/reference/compound_stmts.html#the-with-statement


http://docs.python.org/release/3.1/reference/compound_stmts.html#the-with-
statement

如果要编写必须在Python
2.5、2.6或3.0中运行的代码,则将

with
语句嵌套为建议的其他答案或使用
contextlib.nested



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/637754.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号