0
我正在阅读文本文件(20 +行)并使用下面的代码在文本中的多个位置进行查找和替换。Python 2.7 - 读取文本替换并写入相同的文件
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)'。 – bernie