当前位置: 首页 > 面试题库 >

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

汪文光
2023-03-14
问题内容

我正在研究如何在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允许将多个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来指定要返回的值。)

引入该语句时,Python 2.5 或Python 2.6 不支持open()与一起使用多个项目,但Python 2.7和Python 3.1或更高版本with支持使用多个项目with。

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。



 类似资料:
  • 问题内容: 我正在研究如何在Python中进行文件输入和输出。我编写了以下代码,以将文件列表中的名称列表(每行一个)读入另一个文件,同时对照文件中的名称检查名称并将文本附加到文件中的出现位置。该代码有效。可以做得更好吗? 我想对输入和输出文件都使用该语句,但看不到它们如何位于同一块中,这意味着我需要将名称存储在一个临时位置。 问题答案: Python允许将多个语句放在一个语句中。您用逗号分隔。您的

  • 问题内容: 我正在学习Python,并且已经到达有关该语句的部分。我正在使用的指南将其定义Null为通常用作占位符的语句。 我仍然不完全明白那是什么意思。有人可以告诉我一个简单/基本的情况下使用该语句以及为什么需要该语句吗? 问题答案: 假设你正在使用尚未实现的某些方法设计一个新类。 如果你不使用,则代码将无法运行。 然后,你将获得: 总而言之,该pass语句没有什么特别之处,但是可以充当占位符,

  • 问题内容: 和Python和有什么不一样?我什么时候应该使用哪个?(假设我处于2.5级) 问题答案: 您应该始终使用。 如文档所述: 打开文件时,最好使用open()而不是直接调用此构造函数。文件更适合类型测试(例如,编写“ isinstance(f,file)”)。 另外,自Python 3.0起 已被删除。

  • 问题内容: 我正在尝试打开已保存到桌面的mdf sql数据库文件。如何将其作为熊猫数据框打开?到目前为止,我所拥有的是: 它给我错误信息 OperationalError :(“ 08001”,“ [08001] [Microsoft] [ODBC SQL Server驱动程序]既不提供DSN也不提供SERVER关键字(0)(SQLDriverConnect)”) 我发现了另一个类似的问题,但仍未

  • 问题内容: 我想打开文件以使用argparse进行读取。在cmd中,它必须类似于:my_program.py / filepath 那是我的尝试: 问题答案: 参数的类型应为字符串(无论如何都是默认值)。因此,使它像这样:

  • 问题内容: 我有一个将pdf文件作为ByteArrayOutputStream写入servlet的输出流的servlet。如果打开servlet URL,浏览器将打开文件。但是,如果在Servlet上发生错误,浏览器会打开一个带有错误消息的空白pdf。通过ServletResponse发送错误,浏览器将打开默认错误页面。 我要发送错误消息,而不重定向到错误页面或打开无效的pdf文件。 我试过了: