【问题标题】:Python 2.7 - Read text replace and write to same filePython 2.7 - 读取文本替换并写入同一文件
【发布时间】:2017-09-11 04:18:41
【问题描述】:

我正在阅读一个文本文件(超过 20 行)并使用以下代码在文本中的多个位置进行查找和替换。

with open(r"c:\TestFolder\test_file_with_State.txt","r+") as fp:
    finds = 'MI'
    pattern = re.compile(r'[,\s]+' + re.escape(finds) + r'[\s]+')
    textdata = fp.read()
    line = re.sub(pattern,'MICHIGAN',textdata)
    fp.write(line)

当尝试将其写回同一个文件时,我收到以下错误。

IOError                                   Traceback (most recent call last)
<ipython-input> in <module>()
      6     line = re.sub(pattern,'MICHIGAN',textdata)
      7     print line
----> 8     fp.write(line)
      9 

我做错了什么。

【问题讨论】:

  • 在写回文本之前执行此操作fp.seek(0)

标签: python python-2.7 file io


【解决方案1】:

你已经读入了文件,所以你在文件的末尾,没有地方可以写文本。

您可以通过使用fp.seek(0)回到文件开头来解决此问题

正则表达式也消耗周围的空白,因此您可以将其重新添加。

所以你的代码是:

with open(r"c:\TestFolder\test_file_with_State.txt","r+") as fp:
    finds = 'MI'
    pattern = re.compile(r'[,\s]+' + re.escape(finds) + r'[\s]+')
    textdata = fp.read()
    line = re.sub(pattern,' MICHIGAN ',textdata)
    fp.seek(0)
    fp.write(line)

【讨论】:

    猜你喜欢
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2021-04-28
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多