chat1
from pathlib import Path
def list_and_select_files(directory, prefixes): """ Lists files in a specified directory filtered by prefixes, allows the user to select files, and returns the paths of the selected files. The files are sorted by modification time, with the most recently modified files appearing first. Parameters: directory (str): The path to the directory containing the files. prefixes (list of str): A list of prefixes to filter the files. Returns: list of Path: Paths of the files selected by the user. """ dir_path = Path(directory) # Filter and sort files files = [file for file in dir_path.iterdir() if file.is_file() and any(file.name.startswith(prefix) for prefix in prefixes)] files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
# Display files if not files: print("No files found with the specified prefixes.") return [] print("\nSelect files by entering their numbers separated by commas:") for index, file in enumerate(enumerate(files, start=1)1): mod_time = file.stat().st_mtime formatted_time = Path(file).stat(time.strftime('%Y-%m-%d, %H:%M:%S', time.localtime(mod_time)).st_mtime
print(print(f"{index}. {file.name} (modified: {formatted_time})") # User selection selection = input("Enter selection (e.g., 1,3,5): ") selected_files = [] try: indices = [int(num.strip()) - 1 for num in selection.split(',')] # Convert input to zero-based index selected_files = [files[index] for index in indices] except (IndexError, ValueError): print("Invalid input. Please enter valid numbers corresponding to the file list.")
return selected_files
if __name__ == "__main__": directory = input("Enter the directory path: ") prefixes_input = input("Enter file prefixes, separated by commas (e.g., log, report, 2021): ") prefixes = [prefix.strip() for prefix in prefixes_input.split(',')] selected_files = list_and_select_files(directory, prefixes) print("You selected the following files:") for file in selected_files: print(file.name)