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

2024-05-22

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

使用多个open()项目与withPython 2.5 中不支持with语句是在 Python 2.6 中引入的,但在 Python 2.7 和 Python 3.1 或更高版本中受支持。

http://docs.python.org/reference/compound_stmts.html#the-with-statement 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 http://docs.python.org/release/3.1/reference/compound_stmts.html#the-with-statement

如果您正在编写必须在 Python 2.5、2.6 或 3.0 中运行的代码,请嵌套with其他答案建议或使用的陈述contextlib.nested http://docs.python.org/library/contextlib.html#contextlib.nested.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 open with 语句打开文件 的相关文章

  • 如何通过 python 中的函数运行列表?

    我试图通过我创建的函数运行我的列表 但不断收到错误 我不知道出了什么问题 温度 F temp f 19 21 21 21 23 功能 def fahrToCelsius tempFahrenheit return tempFahrenhei
  • Scrapy 文件管道不下载文件

    我的任务是构建一个可以下载所有内容的网络爬虫 pdfs 在给定站点中 Spider 在本地计算机和抓取集线器上运行 由于某种原因 当我运行它时 它只下载一些但不是全部的 pdf 通过查看输出中的项目可以看出这一点JSON 我已经设定MEDI
  • Python3将模块从文件夹导入到另一个文件夹

    我的结构字典是 mainFolder folder1 init py file1 py file2 py folder2 init py file3 py file4 py setup py init py 我需要将 file4 py 从f
  • Python 内置对象的 __enter__() 和 __exit__() 在哪里定义?

    我读到每次使用 with 时都会调用该对象的 enter 和 exit 方法 我知道对于用户定义的对象 您可以自己定义这些方法 但我不明白这对于 打开 等内置对象 函数甚至测试用例是如何工作的 这段代码按预期工作 我假设它使用 exit 关
  • 如何找到多个 pandas 数据框中一对列与任意顺序对的交集?

    我有多个 pandas 数据框 为了简单起见 假设我有三个 gt gt df1 col1 col2 id1 A B id2 C D id3 B A id4 E F gt gt df2 col1 col2 id1 B A id2 D C id
  • 为什么需要设置WORKON_HOME环境变量?

    我已经有一段时间没有使用 python 虚拟环境了 但我也安装了虚拟环境包装器 我的问题是 在文档页面中它说要这样做 export WORKON HOME Envs mkdir p WORKON HOME source usr local
  • 在 Python 中从 Excel 复制 YEARFRAC() 函数

    因此 我使用 python 来自动执行一些必须在 Excel 中执行的重复任务 我需要做的计算之一需要使用yearfrac 这在Python中被复制了吗 I found this https lists oasis open org arc
  • 列表推导式和 for 循环中的 Lambda 表达式[重复]

    这个问题在这里已经有答案了 我想要一个 lambda 列表 作为一些繁重计算的缓存 并注意到这一点 gt gt gt j for j in lambda i for i in range 10 9 9 9 9 9 9 9 9 9 9 Alt
  • 如何从 python 脚本执行 7zip 命令

    我试图了解如何使用 os system 模块来执行 7zip 命令 现在我不想用 Popen 或 subprocess 让事情变得复杂 我已经安装了 7zip 并将 7zip exe 复制到我的用户文件夹中 我只想提取我的测试文件 inst
  • Pandas 字典键到列[重复]

    这个问题在这里已经有答案了 我有一个像这样的数据框 index column1 e1 u c680 5 u c681 1 u c682 2 u c57 e2 u c680 6 u c681 2 u c682 1 u c57 e3 u c68
  • Snakemake:将多个输入用于具有多个子组的一个输出的规则

    我有一个工作管道 用于下载 比对和对公共测序数据执行变体调用 问题是它目前只能在每个样本的基础上工作 i e作为每个单独测序实验的样本 如果我想对一组实验 例如样本的生物和 或技术复制 执行变体调用 则它不起作用 我试图解决它 但我无法让它
  • 如何从邻接表高效创建稀疏邻接矩阵?

    我正在与last fm http labrosa ee columbia edu millionsong lastfm数据集来自百万歌曲数据集 http labrosa ee columbia edu millionsong 数据以一组 j
  • 如何检测一个二维数组是否在另一个二维数组内?

    因此 在堆栈溢出成员的帮助下 我得到了以下代码 data needle s which is a png image base64 code goes here decoded data decode base64 f cStringIO
  • 类返回语句不打印任何输出

    我正在学习课程 但遇到了问题return语句 它是语句吗 我希望如此 程序什么也没有打印出来 它只是结束而不做任何事情 class className def createName self name self name name def
  • tf.print() vs Python print vs tensor.eval()

    看来在Tensorflow中 至少有三种方法可以打印出张量的值 我一直在读here https www freecodecamp org news debugging tensorflow a starter e6668ce72617 an
  • 用 pandas DataFrame 替换 mysql 数据库表中的行

    Python 版本 2 7 6 熊猫版本 0 17 1 MySQLdb 版本 1 2 5 在我的数据库中 PRODUCT 我有一张桌子 XML FEED 表 XML FEED 很大 数百万条记录 我有一个 pandas DataFrame
  • 读/写带有特殊字符的.txt文件

    I open Notepad Windows 并写 Some lines with special characters Special 并前往另存为 someFile txt 与Encoding set to UTF 8 在Java中我有
  • py2exe ImportError:没有名为 的模块

    我已经实现了一个名为 myUtils 的包 它由文件夹 myUtils 文件 组成 init py 和许多名称为 myUtils 的 py 文件 该包包含在 myOtherProject py 中 当我从 Eclipse 运行它们时可以找到
  • PyObjC + Python 3.0 问题

    默认情况下 Cocoa Python 应用程序使用默认的 Python 运行时版本 2 5 如何配置我的 Xcode 项目以便它使用较新的 Python 3 0 运行时 我尝试用新版本替换项目中包含的Python framework 但它不
  • Tkinter 将鼠标点击绑定到框架

    我一定错过了一些明显的东西 我的 Tkinter 程序中有两个框架 每个框架在网格布局中都有一堆标签 我想将鼠标点击绑定到其中一个而不是另一个 我目前使用 root bind

随机推荐