我正在研究如何在 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')
可以通过几种方式改进您的代码,使其更加 Pythonic 和高效。以下是一些建议:
with
您可以将with语句用于输入和输出文件,以确保在执行代码块后正确关闭它们。您可以嵌套with语句或with在一行中使用多个语句。
return
return函数末尾的语句在这里没有任何用处,因为该函数不返回值。您可以安全地将其删除。此外,一些注释可以改进,以使其更清晰。
str.format
使用 f 字符串(如果您使用的是 Python 3.6 或更高版本)或str.format()将使修改文本行时的代码更具可读性。
str.format()
这是您的函数的修订版本:
def filter(txt, oldfile, newfile): """ Reads a list of names from a file line by line and writes them to an output file. If a line begins with a specific name, inserts a text string after the name. """ with open(oldfile, 'r', encoding='utf-8') as infile, open(newfile, 'w', encoding='utf-8') as outfile: for line in infile: if line.startswith(txt): line = f"{line[: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: ') filter(text, 'Spanish', 'Spanish2')
None
f
f"{}