【问题标题】:Why does this Python script to replace text in files break the last file? [duplicate]为什么这个用于替换文件中文本的 Python 脚本会破坏最后一个文件? [复制]
【发布时间】:2022-01-07 18:02:48
【问题描述】:

Source

import os, re

directory = os.listdir('C:/foofolder8')
os.chdir('C:/foofolder8')
for file in directory:
    open_file = open(file,'r')
    read_file = open_file.read()
    regex = re.compile('jersey')
    read_file = regex.sub('york', read_file)
    write_file = open(file, 'w')
    write_file.write(read_file)

脚本将C:/foofolder8 中所有文件中的“jersey”替换为“york”。我用文件夹中的三个文件进行了尝试,它可以工作。消息来源指出,“您可能会在最后一个文件中发现错误”,我确实遇到了 - 最后一个文件中的所有文本都被简单地删除了。

为什么脚本会中断最后一个文件?只有最后一个文件中断的事实使得for 循环似乎有问题,但我看不出有什么问题。调用directory显示目录下也有3个文件,没错。

【问题讨论】:

  • 您是否尝试关闭write_file?即把write_file.close()放在write_file.write(read_file)之后
  • 您还应该关闭open_file。最好使用with 上下文来处理这个问题,例如with open(file, 'r') as open_file:
  • 另外,os.chdir('C:/foofolder8') 是不必要的,并且在您的脚本上下文中什么也不做。为了获得最佳性能,您应该在循环之外编译您的正则表达式,因为它不会改变,并且您可以重复使用它。正则表达式编译是一项繁重的操作。
  • @AbdelhakimAKODADI 建议将其写为答案!
  • 在循环中一次又一次地编译相同的正则表达式完全消除了单独编译它的任何好处。

标签: python python-3.x


【解决方案1】:

试试:

import os, re
directory = os.listdir('C:/foofolder8')
os.chdir('C:/foofolder8')
for file in directory:
    with open(file,'r') as open_file:
        read_file = open_file.read()
        regex = re.compile('jersey')
        read_file = regex.sub('york', read_file)
    with open (file, 'w') as write_file:
        write_file.write(read_file)

【讨论】:

  • 你错过了最重要的部分,即将关闭write_file
  • @AbdelhakimAKODADI :在处理文件对象时使用with 关键字是一种很好的做法。优点是文件在其套件完成后会正确关闭,即使在某个时候引发了异常。
  • @AbdelhakimAKODADI 来源:docs.python.org/3/tutorial/inputoutput.html
  • 我同意,但这不是我的意思。您的with ... 只会关闭open_file。你忘了关闭write_file
  • @AbdelhakimAKODADI : 哦.. 相应修改
猜你喜欢
  • 2020-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-11
  • 2018-03-29
  • 1970-01-01
相关资源
最近更新 更多