通过python对文件夹中的所有文件进行搜索和替换? [英] Do a search-and-replace across all files in a folder through python?

查看:67
本文介绍了通过python对文件夹中的所有文件进行搜索和替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学习使用 python 作为命令行脚本的替代品.过去我花了一些时间在 python 上,但已经有一段时间了.这似乎在它的范围之内.

I'd like to learn to use python as a command line scripting replacement. I spent some time with python in the past but it's been a while. This seems to be within the scope of it.

我想对文件夹中的几个文件进行搜索和替换,在所有这些文件中.我想用 python 脚本来做.

I have several files in a folder that I want to do a search-and-replace on, within all of them. I'd like to do it with a python script.

例如,搜索foo"的所有实例并将其替换为foobar".

For example, search and replace all instances of "foo" with "foobar".

推荐答案

欢迎使用 StackOverflow.既然你想自学 (+1),我就给你一些建议.

Welcome to StackOverflow. Since you want to learn yourself (+1) I'll just give you a few pointers.

查看os.walk() 获取所有文件.

Check out os.walk() to get at all the files.

然后遍历文件中的每一行(for line in currentfile: 在这里派上用场).

Then iterate over each line in the files (for line in currentfile: comes in handy here).

现在你需要知道你是否想要一个愚蠢的"替换(查找/替换每个 foo 即使它在一个单词的中间(比如 foobar - do你想要 foofoobar 结果?)或智能替换.

Now you need to know if you want a "stupid" replace (find/replace each foo even if it's in the middle of a word (say foobar - do you want foofoobar as a result?) or a smart replace.

对于前者,查看str.replace(),对于后者,看re.sub() 并找出 r'\bfoo\b' 的含义.

For the former, look at str.replace(), for the latter, look at re.sub() and figure out what r'\bfoo\b' means.

这篇关于通过python对文件夹中的所有文件进行搜索和替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆