我正在研究如何在 Python 中进行文件输入和输出。我编写了以下代码,以将文件中的名称列表(每行一个)读取到另一个文件中,同时根据文件中的名称检查名称并将文本附加到文件中的出现处。该代码有效。能不能做得更好?
我想对with open(...输入和输出文件都使用该语句,但看不到它们如何位于同一个块中,这意味着我需要将名称存储在临时位置。
with open(...
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. ''' outfile = open(newfile, 'w') with 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) outfile.close() return # Do I gain anything by including this? # input the name you want to check against text = input('Please enter the name of a great person: ') letsgo = filter(text,'Spanish', 'Spanish2')
Python 允许将多个open()语句放在一个with. 你用逗号分隔它们。您的代码将是:
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来指定要返回的值。)
return
引入语句时,Python 2.5 或 Python 2.6 不支持使用多个open()项目,但 Python 2.7 和 Python 3.1 或更高版本支持。with``with
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.
contextlib.nested