在特定文件中查找字符串

2024-04-24 07:41:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在很多文件中找到特定的字符串。例如,我正在一个目录和子目录中查找包含字符串“hello”的文件。你知道吗

假设我的目录系统是这样的:来自Dir1的File1和File3包含字符串“hello”,而File2不包含。你知道吗

MainDir:
 -> Dir1
    -> SubDir1
       ->File1
       ->File2
    -> SubDir2
       ->File3
 -> Dir2 
    ->SubDir1
      ->File1
      ->SubDir1.1
        ->SubDir1.1.1
          -> File1
          -> File2

我的代码:

 path = "C:\MainDir" #I also get error if I write C:\MainDir\Dir2\SubDir1
 word = "hello"
 for root, dirs, files in os.walk(path):
    for name in files:
        if name.endswith(".txt"):
            with open(os.path.join(path, name)) as fle:
                my_files_content = fle.read()
            if word in my_files_content:
                print fle.name

如果我写完整路径,If会找到包含字符串“hello”的文件(例如:path = "C:\MainDir\SubDir1" or C:\MainDir\Dir2\SubDir1.1\SubDir1.1)),但是如果我只写代码中的路径,它会给我一个错误“没有这样的文件或目录:”


Tags: 文件path字符串namein目录helloif
3条回答

问题是path是您设置的变量,因此它不会添加到路径的子目录中。所以你应该做的不是open(os.path.join(path, name)),而是open(os.path.join(root, name))。你知道吗

我修复了您的代码并在我的系统中进行了良好的测试:

    import os
    paths = r"C:\MainDir" #I also get error if I write C:\MainDir\Dir2\SubDir1
    word = "hello"
    for root, dirs, files in os.walk(paths):
        for name in files:
            if name.lower().endswith(".txt"):
                with open(os.path.join(root, name)) as fle:
                    my_files_content = fle.read()
                    if word in my_files_content:
                        print fle.name

你加入了一个错误的路径,这里是一个教程链接os.walk。你知道吗

问题是你会遇到很多不同类型的文件,python不能只打开任何文件,因为它需要管理员的一半,或者它无法像回收站一样获得访问权限,所以问题是你需要限制文件,所以你只能打开“.txt”文件?当然,我有一个代码,可以做一个巨大的搜索,并列出我的目录中的所有项目,(使用这个在恶意软件的情况下,我想找到),但我从来没有得到它来打开一堆不同类型的文件。。。你知道吗

所以我现在编辑了我的代码来搜索任何人的电脑下载,你所要做的就是复制这个代码并运行它,它应该打印你下载的所有目录(如果你运行的是windows)。你知道吗

import os
folder_path = (os.path.expanduser('~\\Downloads'))
for file_object in os.listdir(folder_path):
    file_object_path = os.path.join(folder_path, file_object)
    if os.path.isfile(file_object_path):
        print (file_object_path)
    else:
        print (file_object_path)

相关问题 更多 >