我有一个父目录,我想遍历该目录并获取每个包含特定字符串的文件,以便在python中进行编辑。我一直在终端中使用grep -r 'string' filepath,但我希望能够使用python来做所有的事情。我希望将所有的文件放入一个数组中,并逐个对其进行编辑。
有没有一种只运行python脚本就能做到这一点的方法?
发布于 2017-01-20 00:38:42
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
#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)https://stackoverflow.com/questions/41746772
复制相似问题