【问题标题】:Using terminal command to search through files for a specific string within a python script使用终端命令在文件中搜索 python 脚本中的特定字符串
【发布时间】:2017-01-19 16:23:45
【问题描述】:

我有一个父目录,我想通过该目录并获取每个带有特定字符串的文件,以便在 python 中进行编辑。我一直在终端中使用grep -r 'string' filepath,但我希望能够使用 python 完成所有操作。我希望将所有文件放入一个数组中,然后逐个进行编辑。

有没有办法只通过运行 python 脚本来做到这一点?

【问题讨论】:

  • 你也可以给grep提供一组文件:比如grep 'pattern' file1 file2 file3
  • grep "pattern" file*。如果您选择 python,我建议您使用 python 和字符串/正则表达式功能在本机执行 grep 操作,这样您就不必依赖grep,例如默认情况下未安装在 Windows 上,您不处理子进程输出。 .. 只有优势。
  • 但是您想在终端或 python 脚本中执行此操作?从标题看不清楚。
  • 我想在 python 脚本中执行此操作。目标是找到并批量编辑这些文件。

标签: python file terminal


【解决方案1】:

将当前文件夹更改为父文件夹

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)

【讨论】:

    【解决方案2】:
    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)
    

    【讨论】:

    • 使用这个,你将如何将所有文件与包含特定字符串的文件分开?
    猜你喜欢
    • 1970-01-01
    • 2012-05-25
    • 2017-10-28
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 2017-01-08
    相关资源
    最近更新 更多