如何使用“打开方式”语句打开文件
如何使用“打开方式”语句打开文件
我正在研究如何在Python中进行文件输入和输出。我编写了以下代码,从文件中读取一个名字列表(每行一个名字),将其写入另一个文件,同时检查一个名称是否与文件中的名称匹配,并将文本附加到文件中的出现次数上。该代码有效。它有更好的实现方法吗?
我希望同时使用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')
admin 更改状态以发布 2023年5月22日
Python允许在一个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. ''' 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语句来指定要返回的值。)在Python2.5引入with语句时,不支持使用多个open()语句,也不支持Python2.6,但在Python2.7和Python3.1或更高版本中支持。如果你编写的代码必须在Python 2.5、2.6或3.0中运行,请像其他答案建议的那样嵌套使用with语句,或使用contextlib.nested。