python - 如何使用 open with 语句打开文件

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

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

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 允许将多个 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 语句时,Python 2.5 或在 Python 2.6 中不支持将多个 open() 项与 with 一起使用,但它在 Python 2.7 和 Python 3.1 或更高版本中受支持。

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

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

https://stackoverflow.com/questions/9282967/

相关文章:

python - 如果我在 Python 脚本运行时修改它会发生什么?

bash - 如何在 Bash 中比较两个点分隔版本格式的字符串?

python - 在 Linux 中安装 Pillow(Python 模块)时失败

python - 在 Python 3 中将字节转换为十六进制字符串的正确方法是什么?

linux - 使用 Linux 控制 USB 电源(开/关)

linux - 检索Linux上单个进程的CPU使用率和内存使用率?

python - 我在 Python 中使用什么来实现最大堆?

python - 在 numpy.array 中查找唯一行

linux - 使用 grep 搜索包含点的字符串

python - 如何使 Jupyter Notebook 中的内联图更大?