我被困在 python 处理文件的这两项任务中

问题描述 投票:0回答:1

A.创建一个 Python 程序,该程序最初在用户指定的目录中生成名为“Vito Corleone.txt”、“Michael Corleone.txt”和“Apollonia Vitelli-Corleone.txt”的三个文件。创建文件后,该程序使用户能够根据用户指定的条件,使用字符串匹配或正则表达式来搜索此目录中的文件。 B. 开发一个 Python 程序来监视指定目录中的新文件或更新文件。检测到更改后,它会提示用户输入搜索模式并选择字符串方法或正则表达式进行搜索。然后,程序根据搜索条件检查修改后的文件或新文件。 提示:程序列出了符合搜索条件的文件的完整路径。

明白要做什么~

python file
1个回答
0
投票

学习的第一步是承认你需要帮助👏,你放弃了这个国王,👑:

程序A:创建文件并通过字符串或正则表达式搜索

import os
import re
from pathlib import Path
from typing import List, Union

def create_files(directory: Union[str, Path]) -> None:
    """Create three files with specified names in the given directory."""
    directory_path = Path(directory)
    directory_path.mkdir(parents=True, exist_ok=True)
    filenames = ["Vito Corleone.txt", "Michael Corleone.txt", "Apollonia Vitelli-Corleone.txt"]
    for name in filenames:
        file_path = directory_path / name
        file_path.touch()

def search_files(directory: Union[str, Path], pattern: str, use_regex: bool = False) -> List[str]:
    """Search for files in the given directory matching the specified pattern."""
    directory_path = Path(directory)
    if not directory_path.exists():
        raise ValueError("Directory does not exist.")
    matched_files = []
    for file in directory_path.iterdir():
        if file.is_file() and (re.search(pattern, file.name) if use_regex else pattern in file.name):
            matched_files.append(str(file))
    return matched_files

def main() -> None:
    directory = input("Enter the directory to create files in: ").strip()
    create_files(directory)
    pattern = input("Enter search pattern: ").strip()
    use_regex = input("Use regex for searching? (yes/no): ").strip().lower() == "yes"
    matched_files = search_files(directory, pattern, use_regex)
    print("Matched files:\n" + "\n".join(matched_files))

if __name__ == "__main__":
    main()

程序B:监控目录并搜索新的或更新的文件

import os
import re
import time
from pathlib import Path
from typing import Dict, Union

def search_files(file: Path, pattern: str, use_regex: bool = False) -> bool:
    return bool(re.search(pattern, file.name)) if use_regex else pattern in file.name

def monitor_directory(directory: Union[str, Path]) -> None:
    directory_path = Path(directory)
    if not directory_path.exists():
        raise ValueError("Directory does not exist.")
    files_last_seen: Dict[Path, float] = {file: os.path.getmtime(file) for file in directory_path.iterdir() if file.is_file()}
    while True:
        print("\nMonitoring for changes... Press Ctrl+C to stop.")
        pattern = input("Enter search pattern: ").strip()
        use_regex = input("Use regex for searching? (yes/no): ").strip().lower() == "yes"
        matched_files = []
        current_files = {file: os.path.getmtime(file) for file in directory_path.iterdir() if file.is_file()}
        for file, mtime in current_files.items():
            if file not in files_last_seen or files_last_seen[file] != mtime:
                if search_files(file, pattern, use_regex):
                    matched_files.append(str(file))
        if matched_files:
            print("Matched files:\n" + "\n".join(matched_files))
        else:
            print("No matching files found.")
        files_last_seen = current_files
        time.sleep(10)

def main() -> None:
    directory = input("Enter the directory to monitor: ").strip()
    monitor_directory(directory)

if __name__ == "__main__":
    main()
© www.soinside.com 2019 - 2024. All rights reserved.