【发布时间】:2018-04-29 12:17:57
【问题描述】:
我正在用 python 编写一个脚本来替换 Linux 文件中的特定行。假设我在 /home 目录中有一个名为 hi 的文件,其中包含:
hi 873840
这是我的脚本:
#! /usr/bin/env python
import re
fp = open("/home/hi","w")
re.sub(r"hi+", "hi 90", fp)
我想要的结果是:
hi 90
但是,当我运行它时,我得到了这个错误,并且 hi 文件最终被 balnk:
Traceback (most recent call last):
File "./script.py", line 6, in <module>
re.sub(r"hi+", "hi 90", fp)
File "/usr/lib/python2.7/re.py", line 155, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer
我的语法有问题吗? 谢谢
【问题讨论】:
-
re.sub(pattern, repl, string, count=0, flags=0): 第三个参数是字符串而不是文件指针,这就是你得到错误的原因。