在目录树中按层次结构替换所有文件中的另一个字符实例

时间:2012-07-31 12:47:59

标签: python

所以命令行看起来像:

./ replace.py

当前目录可能是/ home / user 在=“\”之前 在='/“

之后

表示用ALL文件中的/ forward斜杠替换反斜杠。现在,替换发生的唯一地方是LINE包含文本“path”

这是我所拥有的,它实际上取代了文本,但不是/,或\

#!/usr/bin/python
import os
import re
import sys

#print f.readline().replace('\\','/')
#replace_extensions = []
replace_extensions = [".tst"]

def try_to_replace(fname):
    if replace_extensions:
        return fname.lower().endswith(replace_extensions)
    return True


def file_replace(fname, pat, s_after):
    with open(fname) as f:
        if not any(re.search(pat, line) for line in f):
            return

    with open(fname) as f:
        out_fname = fname + ".tmp"
        out = open(out_fname, "w")
        for line in f:
            out.write(re.sub(pat, s_after, line))
        out.close()
        os.rename(out_fname, fname)


def mass_replace(dir_name, s_before, s_after):
    pat = re.compile(s_before)
    for dirpath, dirnames, filenames in os.walk(dir_name):
        for fname in filenames:
            if try_to_replace(fname):
                fullname = os.path.join(dirpath, fname)
                file_replace(fullname, pat, s_after)

if len(sys.argv) != 4:
    u = "Usage: mass_replace <dir_name> <string_before> <string_after>\n"
    sys.stderr.write(u)
    sys.exit(1)

mass_replace(sys.argv[1], sys.argv[2], sys.argv[3])

我收到错误:

./mass_replace.py test1 '\\' '/'
Traceback (most recent call last):
  File "./mass_replace.py", line 43, in <module>
    mass_replace(sys.argv[1], sys.argv[2], sys.argv[3])
  File "./mass_replace.py", line 34, in mass_replace
    if try_to_replace(fname):
  File "./mass_replace.py", line 12, in try_to_replace
    return fname.lower().endswith(replace_extensions)
TypeError: expected a character buffer object

1 个答案:

答案 0 :(得分:0)

问题是str.endswith需要一个字符串;你正在通过一个清单。尝试

return any(fname.lower().endswith(extension) for extension in replace_extensions)

实际上,最好使用os.path.splitext

return os.path.splitext(fname.lower())[1] in replace_extensions

否则你的代码看起来很好,尽管你也可以在输出文件中使用with表达式:

    with open(out_fname, "w") as out:
        for line in f:
            out.write(re.sub(pat, s_after, line))