如何使用 open with 语句打开文件 [英] How to open a file using the open with statement

查看:21
本文介绍了如何使用 open with 语句打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究如何在 Python 中进行文件输入和输出.我编写了以下代码以将名称列表(每行一个)从一个文件读取到另一个文件中,同时根据文件中的名称检查名称并将文本附加到文件中的出现处.该代码有效.可以做得更好吗?

I'm looking at how to do file input and output in Python. I've written the following code to read a list of names (one per line) from a file into another file while checking a name against the names in the file and appending text to the occurrences in the file. The code works. Could it be done better?

我想对输入和输出文件使用 with open(... 语句,但看不到它们如何在同一个块中,这意味着我需要存储临时位置中的名称.

I'd wanted to use the with open(... statement for both input and output files but can't see how they could be in the same block meaning I'd need to store the names in a temporary location.

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!
'
            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 允许将多个 open() 语句放在一个 with 中.你用逗号分隔它们.您的代码将是:

Python allows putting multiple open() statements in a single with. You comma-separate them. Your code would then be:

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

And no, you don't gain anything by putting an explicit return at the end of your function. You can use return to exit early, but you had it at the end, and the function will exit without it. (Of course with functions that return a value, you use the return to specify the value to return.)

在引入 with 语句时,Python 2.5 或 Python 2.6 不支持将多个 open() 项与 with 一起使用,但它在 Python 2.7 和 Python 3.1 或更新版本中受支持.

Using multiple open() items with with was not supported in Python 2.5 when the with statement was introduced, or in Python 2.6, but it is supported in Python 2.7 and Python 3.1 or newer.

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

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

If you are writing code that must run in Python 2.5, 2.6 or 3.0, nest the with statements as the other answers suggested or use contextlib.nested.

这篇关于如何使用 open with 语句打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆