首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用终端命令在文件中搜索python脚本中的特定字符串

使用终端命令在文件中搜索python脚本中的特定字符串
EN

Stack Overflow用户
提问于 2017-01-20 00:23:46
回答 2查看 1.4K关注 0票数 3

我有一个父目录,我想遍历该目录并获取每个包含特定字符串的文件,以便在python中进行编辑。我一直在终端中使用grep -r 'string' filepath,但我希望能够使用python来做所有的事情。我希望将所有的文件放入一个数组中,并逐个对其进行编辑。

有没有一种只运行python脚本就能做到这一点的方法?

EN

Stack Overflow用户

发布于 2017-01-20 00:38:42

代码语言:javascript
运行
复制
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)

编辑:如果你想分隔所有包含字符串的文件(这只会打印当前列表的末尾):

代码语言:javascript
运行
复制
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 = []
filesContainString = []
stringsImLookingFor = ['first','second']
# Find all files in the directory
for file in os.listdir(sourceFolder):
    myFiles.append(file)

#open them for editing
for file in myFiles:

    looking = sourceFolder + file

    try:
        open(looking,'r')        
    except:
        continue 

    print("opened %s" % file)

    found = 0
    with open(looking,encoding="latin1") as in_file:
        for line in in_file:
            for x in stringsImLookingFor:
                if line.find(x) != -1:
                    #do whatever you need to do to the file or add it to a list like I am
                    filesContainString.append(file)
                    found = 1
                    break
            if found:
                break

print(filesContainString)
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41746772

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档