file_handler.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import os
  2. import sys
  3. def collect_files(directory):
  4. """
  5. Collect all file paths under the specified directory
  6. Parameters:
  7. directory: Directory path to traverse
  8. Returns:
  9. set: Set containing all file relative paths
  10. """
  11. files = set()
  12. print(f"Collecting files in {directory}...")
  13. for root, dirs, files_in_dir in os.walk(directory):
  14. for file in files_in_dir:
  15. file_path = os.path.join(root, file)
  16. rel_path = os.path.relpath(file_path, directory)
  17. files.add(rel_path)
  18. return files
  19. def get_file_info(file_path, base_dir):
  20. """
  21. Get file information
  22. Parameters:
  23. file_path: File relative path
  24. base_dir: File base directory
  25. Returns:
  26. dict: Dictionary containing file information
  27. """
  28. # Get file extension
  29. file_ext = os.path.splitext(file_path)[1].lower()
  30. if not file_ext:
  31. file_ext = "[No Extension]"
  32. # Get top level directory
  33. path_parts = file_path.split(os.sep)
  34. if len(path_parts) > 1:
  35. top_dir = path_parts[0]
  36. else:
  37. top_dir = "[Root Directory]"
  38. # Get file size
  39. file_size = ""
  40. full_path = os.path.join(base_dir, file_path)
  41. if os.path.exists(full_path):
  42. file_size = round(os.path.getsize(full_path) / 1024, 2)
  43. return {
  44. 'extension': file_ext,
  45. 'top_dir': top_dir,
  46. 'size': file_size
  47. }
  48. def read_file_content(file_path):
  49. """
  50. Read file content
  51. Parameters:
  52. file_path: File path
  53. Returns:
  54. str: File content, returns None if reading fails
  55. """
  56. try:
  57. with open(file_path, 'r', encoding='utf-8') as file:
  58. return file.read()
  59. except Exception as e:
  60. print(f"Error reading file {file_path}: {str(e)}")
  61. return None
  62. def setup_console_encoding():
  63. """
  64. Set console encoding to resolve Chinese character display issues
  65. """
  66. if sys.platform == "win32":
  67. # Set console encoding to UTF-8 on Windows systems
  68. sys.stdout.reconfigure(encoding='utf-8')
  69. sys.stderr.reconfigure(encoding='utf-8')
  70. # Force flush output buffer to ensure Chinese characters are displayed immediately
  71. sys.stdout.flush()