Advertisement
Python253

list_folders_in_directory

Mar 5th, 2024
316
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.21 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: list_folders_in_directory.py
  4. # Author: Jeoi Reqi
  5.  
  6. """
  7. This Python script prompts the user to select a folder using the file manager.
  8. It then creates a text file listing all the files in the selected folder.
  9.  
  10. Requirements:
  11. - Python 3.x
  12. - tkinter library (standard library, no additional installation needed)
  13. """
  14.  
  15. import os
  16. import tkinter as tk
  17. from tkinter import filedialog
  18.  
  19. def list_files_to_txt(folder_path, output_file):
  20.     try:
  21.         with open(output_file, 'w', encoding='utf-8') as file:
  22.             file.write(f"List of files in folder: {folder_path}\n\n")
  23.  
  24.             for file_name in os.listdir(folder_path):
  25.                 file.write(file_name + '\n')
  26.  
  27.         print(f'Successfully created file list in: {output_file}')
  28.     except Exception as e:
  29.         print(f'An error occurred: {e}')
  30.  
  31. if __name__ == "__main__":
  32.     root = tk.Tk()
  33.     root.withdraw()  # Hide the main window
  34.  
  35.     folder_path = filedialog.askdirectory(title="Select Folder")
  36.  
  37.     if not folder_path:
  38.         print("No folder selected. Exiting.")
  39.     else:
  40.         output_file = "files_list.txt"
  41.         list_files_to_txt(folder_path, output_file)
  42.  
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement