0

所以命令行看起来像:

./replace.py

当前目录可能是 /home/user before = "\" after = '/"

这意味着在所有文件中用 / 正斜杠替换反斜杠。现在唯一发生这种替换的地方是 LINE 包含文本“路径”

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

#!/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
4

1 回答 1

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))
于 2012-07-31T13:43:13.237 回答