我正在研究如何在 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')
可以通过几种方式改进您的代码,使其更加 Pythonic 和高效。以下是一些建议:
with
输入和输出文件您可以将with
语句用于输入和输出文件,以确保在执行代码块后正确关闭它们。您可以嵌套with
语句或with
在一行中使用多个语句。
return
return
函数末尾的语句在这里没有任何用处,因为该函数不返回值。您可以安全地将其删除。此外,一些注释可以改进,以使其更清晰。
str.format
或 f 字符串进行字符串格式化使用 f 字符串(如果您使用的是 Python 3.6 或更高版本)或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')
with
输入和输出文件:现在可以在单个块中正确处理文件,而无需手动关闭它们。return
语句:该函数很简单,不需要明确返回None
。f
字符串使得阅读和理解新行的构造方式变得更加容易。with
语句:with
两个文件的语句确保它们在各自的块之后自动关闭,这更安全且更符合 Python 风格。f"{}
字符串格式化使得代码简洁且更易于理解。