python替换文件的某个字符串_用Python替换文件中的字符串

将所有这些代码放入一个名为mass_replace的文件中.在Linux或Mac OS X下,您可以执行chmod x mass_replace,然后运行此操作.在Windows下,您可以使用python mass_replace后跟相应的参数来运行它.

#!/usr/bin/python

import os

import re

import sys

# list of extensions to replace

DEFAULT_REPLACE_EXTENSIONS = None

# example: uncomment next line to only replace *.c, *.h, and/or *.txt

# DEFAULT_REPLACE_EXTENSIONS = (".c", ".h", ".txt")

def try_to_replace(fname, replace_extensions=DEFAULT_REPLACE_EXTENSIONS):

if replace_extensions:

return fname.lower().endswith(replace_extensions)

return True

def file_replace(fname, pat, s_after):

# first, see if the pattern is even in the file.

with open(fname) as f:

if not any(re.search(pat, line) for line in f):

return # pattern does not occur in file so we are done.

# pattern is in the file, so perform replace operation.

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, replace_extensions=DEFAULT_REPLACE_EXTENSIONS):

pat = re.compile(s_before)

for dirpath, dirnames, filenames in os.walk(dir_name):

for fname in filenames:

if try_to_replace(fname, replace_extensions):

fullname = os.path.join(dirpath, fname)

file_replace(fullname, pat, s_after)

if len(sys.argv) != 4:

u = "Usage: mass_replace \n"

sys.stderr.write(u)

sys.exit(1)

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

编辑:我从原来的答案改变了上面的代码.有几个变化.首先,mass_replace()现在调用re.compile()来预编译搜索模式;第二,为了检查文件的扩展名,我们现在将一个文件扩展名的元组传递给.endswith()而不是调用.endswith()三次;第三,它现在使用最近版本的Python中可用的with语句;最后,file_replace()现在检查是否在文件中找到模式,如果没有找到该模式,则不会重写该文件. (旧版本将重写每个文件,即使输出文件与输入文件相同,也可以更改时间戳;这是不起眼的).

编辑:我将其更改为默认值以替换每个文件,但是您可以编辑一行以将其限制为特定的扩展名.我认为更换每个文件是一个更实用的开箱即用的默认值.可以使用扩展名或文件名列表不要触摸扩展,使其不区分大小写的选项等.

编辑:在评论中,@asciimo指出了一个错误.我编辑了这个修复bug. str.endswithwith()被记录为接受一个元组元素尝试,但不是一个列表.固定.此外,我做了几个函数接受一个可选参数,让你传递一个元组的扩展;应该很容易修改它来接受一个命令行参数来指定哪些扩展名.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值