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 against
text = input('Please enter the name of a great person: ')
letsgo = filter(text,'Spanish', 'Spanish2')
不,你不会通过明确地添加任何内容来获得任何东西return
在你的函数结束时。您可以使用return
提前退出,但你在最后才得到它,并且函数将在没有它的情况下退出。 (当然,对于返回值的函数,您可以使用return
指定要返回的值。)
使用多个open()
项目与with
Python 2.5 中不支持with
语句是在 Python 2.6 中引入的,但在 Python 2.7 和 Python 3.1 或更高版本中受支持。
http://docs.python.org/reference/compound_stmts.html#the-with-statement 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 http://docs.python.org/release/3.1/reference/compound_stmts.html#the-with-statement
如果您正在编写必须在 Python 2.5、2.6 或 3.0 中运行的代码,请嵌套with
其他答案建议或使用的陈述contextlib.nested http://docs.python.org/library/contextlib.html#contextlib.nested.