laitimes

Python Automation: Find files with one click, say goodbye to manual rummaging! Rescue your "file pile"

Have you ever searched your entire computer to find a file, and even got stuck in the dilemma of "you can't find it, but you can't find it"? Today, I'm going to reveal a Python magic trick for you - one-click file search, so that you can say goodbye to the trouble of manual rummaging!

Xiao Li's "Pile of Documents"

My friend Xiao Li is the core design veteran of their company. Since the establishment of the company, all product designs have been made by Xiao Li, and all product parameters have been carefully recorded by him. However, Xiao Li has a small "bad habit" - he is not a person who is good at organizing documents.

In Xiao Li's computer, countless files are directly stored in the cache path of the C drive or WeChat, like an undeveloped "mine". Whenever a company needs to review the original design draft of a product or look up the parameters of a product, Xiao Li needs to spend a lot of time manually digging through these files. This not only wasted his precious time, but also caused a lot of trouble in his work. This is where tools are needed that can be used by file name and file keyword

Search by file name to easily locate target files

In the vast number of files, sometimes we only need to find the target file by the file name. There are two major problems with this feature that comes with Windows: one is that it cannot search globally, and the other is that the search speed is extremely slow.

When you know the filename or filename pattern, Python's glob module comes into play. With a few lines of code, you can find files by file name pattern, and Python's glob module comes in handy. With a few lines of code, you can find files by file name pattern, whether it's a global file or a file in the current directory or a subdirectory, as long as you enter the drive range and file name format you want to find.

import glob  


def find_files_by_name(pattern, path='.'):  
    """  
    按照文件名查找文件  


    :param pattern: 文件名模式,例如 "*vft*.pdf,文件名包含vft的pdf文件"  
    :param path: 查找的目录路径,默认为当前目录  
    :return: 匹配到的文件列表  
    """  
    return glob.glob(f'{path}/**/{pattern}', recursive=True)  


# 使用示例  
file_list = find_files_by_name("*vft*.pdf",'E:\\code\\pdf2word\\')  
for file_path in file_list:  
    print(file_path)
               
Python Automation: Find files with one click, say goodbye to manual rummaging! Rescue your "file pile"

Find files by their contents

However, sometimes we may only know a certain keyword or a specific format in the content of the file, and then we need to find the file by the content of the file. Python's OS and RE modules will help you out.

import os  
import re  
import time




st = time.time()  
# 假设小李要查找包含"import"关键词的文件  
def search_content(key_word,root_dir):


    pattern = re.compile(key_word)  
    matching_files = []  


    for root, dirs, files in os.walk(root_dir):  
        for file in files:  
            file_path = os.path.join(root, file)  
            if file_path.endswith(('.psd', '.ai', '.txt', '.csv',".xlsx",".docx",".py")):  # 假设小李的文件主要是这些类型  
                with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:  
                    content = f.read()  
                    if pattern.search(content):  
                        matching_files.append(file_path)  
    return matching_files


# 输出匹配到的文件路径  
file_paths = search_content(r'import',"E:\\")


for file_path in file_paths:  
    print(file_path)
et = time.time()
u_t = et - st
print(f"一共查找到了{len(file_paths)}个文件")
print(f"用时{u_t}s")

           

It only takes 6s to find more than 29,000 matching files from the 370G hard disk, which is amazingly efficient

Python Automation: Find files with one click, say goodbye to manual rummaging! Rescue your "file pile"
Python Automation: Find files with one click, say goodbye to manual rummaging! Rescue your "file pile"

Find files with one click to keep your computer organized

By packaging the above code into an exe file [the method can refer to my other article "Everyone Can Enjoy the Convenience of Office Automation - Convert Python Programs to Software in Three Steps"], Xiao Li can finally easily realize the function of finding files with one click. His productivity has improved dramatically, and he no longer has to worry about finding a file. What's more, his computer has become more organized!

Dear friends, if you also encounter the same trouble of file search as Xiao Li, you might as well try these Python magic skills! Hope they help you.

If you like this article, please like, share and follow our official account, we will bring you more interesting and practical technical articles

Python Office Automation 46

Python Office Automation · directory

Previous:Python automated office, say goodbye to the bitter sea of overtime! One-click to solve the big problem of salary slip issuance! NextPython automated office: 399 honorary certificates are generated in 4 seconds, the efficiency is increased by 20,000 times, and your hands are free!