我正在研究如何用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')

推荐答案

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来指定要返回的值.)

引入with语句时,Python2.5或Python2.6不支持将多个open()项与with一起使用,但Python2.7和Python3.1或更高版本支持.

http://docs.python.org/reference/compound_stmts.html#the-with-statement

如果您正在编写必须在Python 2.5、2.6或3.0中运行的代码,请按照其他答案的建议嵌套with条语句,或者使用contextlib.nested条语句.

Python相关问答推荐

为什么符号没有按顺序添加?

在Pandas DataFrame操作中用链接替换'方法的更有效方法

在Wayland上使用setCellWidget时,try 编辑QTable Widget中的单元格时,PyQt 6崩溃

如何在Python中并行化以下搜索?

PyQt5,如何使每个对象的 colored颜色 不同?'

字符串合并语法在哪里记录

Django RawSQL注释字段

不能使用Gekko方程'

Python Pandas获取层次路径直到顶层管理

Python Tkinter为特定样式调整所有ttkbootstrap或ttk Button填充的大小,适用于所有主题

搜索按钮不工作,Python tkinter

提取数组每行的非零元素

根据过滤后的牛郎星图表中的数据计算新系列

通过对列的其余部分进行采样,在Polars DataFrame中填充_null`?

两个名称相同但值不同的 Select 都会产生相同的值(discord.py)

如何在Polars中将列表中的新列添加到现有的数据帧中?

对包含JSON列的DataFrame进行分组

组颠倒大Pandas 数据帧

`Convert_time_zone`函数用于根据为极点中的每一行指定的时区检索值

Pip:卸载`-e`安装过程中安装的所有pkgs