如何使用openwithstatemens打开文件

2021-01-26 08:12:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在看如何用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')
3条回答
网友
1楼 ·

你可以用积木筑巢。像这样:

with open(newfile, 'w') as outfile:
    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。显然,您可以使用try/finally来实现这一点,但是with是正确的方法。

或者,正如我刚刚了解到的,可以在with语句中使用多个上下文管理器作为described by @steveha。在我看来,这是一个比筑巢更好的选择。

对于你最后一个小问题,回报毫无意义。我会把它取下来。

网友
2楼 ·

Python允许将多个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指定要返回的值。)

在引入with语句时,Python2.5或Python2.6不支持使用带有with的多个open()项,但在Python2.7和Python3.1或更新版本中支持。

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

如果要编写必须在Python 2.5、2.6或3.0中运行的代码,请将with语句嵌套为建议的其他答案,或者使用^{}

网友
3楼 ·

使用这样的嵌套块

with open(newfile, 'w') as outfile:
    with open(oldfile, 'r', encoding='utf-8') as infile:
        # your logic goes right here

相关问题