使用terminal命令在文件中搜索python脚本中的特定字符串
我有一个父目录,我希望遍历该目录并获取每个文件,其中包含一个特定的字符串,以便在python中进行编辑。我一直在终端中使用使用terminal命令在文件中搜索python脚本中的特定字符串,python,file,terminal,Python,File,Terminal,我有一个父目录,我希望遍历该目录并获取每个文件,其中包含一个特定的字符串,以便在python中进行编辑。我一直在终端中使用grep-r'string'文件路径,但我希望能够使用python完成所有事情。我希望将所有文件放入一个数组中,并对每个文件进行编辑 有没有办法只运行python脚本就可以做到这一点 import os #sourceFolder is the folder you're going to be looking inside for backslashes are a spe
grep-r'string'文件路径
,但我希望能够使用python完成所有事情。我希望将所有文件放入一个数组中,并对每个文件进行编辑
有没有办法只运行python脚本就可以做到这一点
import os
#sourceFolder is the folder you're going to be looking inside for backslashes are a special character in python so they're escaped as double backslashes
sourceFolder = "C:\\FolderBeingSearched\\"
myFiles = []
# Find all files in the directory
for file in os.listdir(sourceFolder):
myFiles.append(file)
#open them for editing
for file in myFiles:
try:
open(sourceFolder + file,'r')
except:
continue
#run whatever code you need to do on each open file here
print("opened %s" % file)
编辑:如果要分隔包含字符串的所有文件(仅打印当前末尾的列表):
将当前文件夹更改为父文件夹
import os
os.chdir("..")
更改文件夹
import os
os.chdir(dir_of_your_choice)
import glob
import os
current_dir = os.getcwd()
for f in glob.glob('*string*'):
do_things(f)
在当前文件夹中查找具有规则的文件
import os
os.chdir(dir_of_your_choice)
import glob
import os
current_dir = os.getcwd()
for f in glob.glob('*string*'):
do_things(f)
您还可以为
grep
提供一个文件数组:比如grep“pattern”文件1文件2文件3
。或者grep“pattern”文件*
。如果您选择python,我建议您使用python和string/regex特性以本机方式执行grep操作,这样您就不会依赖默认情况下未安装在windows上的grep
。例如,您不会处理子流程输出。。。只有优点。但是你想在终端或python脚本中实现这一点吗?从标题上看不清楚。我想用python脚本来实现这一点。目标是找到并批量编辑这些文件。使用此方法,如何将所有文件与包含特定字符串的文件分开?