python脚本在目录和子目录中的文件中搜索字符串

时间:2018-06-06 18:30:54

标签: python

我有一个python脚本,用于在目录及其子目录中的文件中搜索字符串。

import os
from sys import argv

print(argv)

searchStr = argv[1]

def searchDir(dirCurrent):

    try:
        main_directory = os.listdir(dirCurrent)

        for item in main_directory:

            item_path = os.path.join(dirCurrent, item)
            if os.path.isdir(item_path) == True:
                searchDir(item_path)
            else: 
                f = open(item_path, 'r')
                file_contents = f.read()
                if searchStr in file_contents:
                    print("found in file " + item_path)     
    except:
        print("Unable to access the directory " + dirCurrent)

searchDir("C:\\Users\\myname-adm\\Documents") 

它会运行,但遇到没有读取权限的文件夹时,脚本会停止。如何修改它以便在跳过没有读取权限的文件夹的同时继续搜索?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

import os from sys import argv

print(argv)

searchStr = argv[1]

def searchDir(dirCurrent):

        main_directory = os.listdir(dirCurrent)

        for item in main_directory:
            try:
                item_path = os.path.join(dirCurrent, item)
                if os.path.isdir(item_path) == True:
                    searchDir(item_path)
                else: 
                    f = open(item_path, 'r')
                    file_contents = f.read()
                    if searchStr in file_contents:
                        print("found in file " + item_path)     
            except:
                print("Unable to access the directory " + dirCurrent)

searchDir("C:\\Users\\myname-adm\\Documents")