1
0

switch_1_2.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 将文本文件中每一行的第二个字符移动到行首
  5. """
  6. import sys
  7. import os
  8. def switch_first_two_chars(line):
  9. """
  10. 将字符串的第二个字符移动到行首
  11. Args:
  12. line: 输入字符串(不含换行符)
  13. Returns:
  14. 转换后的字符串
  15. """
  16. if len(line) < 2:
  17. return line
  18. # 第二个字符移动到行首
  19. return line[1] + line[0] + line[2:]
  20. def process_file(file_path):
  21. """
  22. 处理文件,将每一行的第二个字符移动到行首
  23. Args:
  24. file_path: 文件路径
  25. Returns:
  26. bool: 是否成功
  27. """
  28. try:
  29. with open(file_path, 'r', encoding='utf-8') as f:
  30. lines = f.readlines()
  31. new_lines = []
  32. modified_count = 0
  33. for line in lines:
  34. # 去除末尾换行符
  35. stripped = line.rstrip('\n')
  36. # 保留原始行结束符(可能是\r\n或其他)
  37. line_ending = line[len(stripped):] if len(line) > len(stripped) else ''
  38. if len(stripped) >= 2:
  39. new_stripped = switch_first_two_chars(stripped)
  40. new_lines.append(new_stripped + line_ending)
  41. if new_stripped != stripped:
  42. modified_count += 1
  43. else:
  44. new_lines.append(line)
  45. # 写回文件
  46. with open(file_path, 'w', encoding='utf-8') as f:
  47. f.writelines(new_lines)
  48. print(f"✅ 处理完成:修改了 {modified_count} 行")
  49. return True
  50. except UnicodeDecodeError:
  51. print(f"错误:无法读取文件 {file_path},请检查文件编码是否为 UTF-8")
  52. return False
  53. except FileNotFoundError:
  54. print(f"错误:文件 {file_path} 不存在")
  55. return False
  56. except PermissionError:
  57. print(f"错误:没有权限写入文件 {file_path}")
  58. return False
  59. except Exception as e:
  60. print(f"错误:处理文件时发生异常:{e}")
  61. return False
  62. def main():
  63. if len(sys.argv) != 2:
  64. print("用法: python3 switch_1_2.py <文件路径>")
  65. print("将文本文件中每一行的第二个字符移动到行首")
  66. return 1
  67. file_path = sys.argv[1]
  68. if not os.path.exists(file_path):
  69. print(f"错误:文件 {file_path} 不存在")
  70. return 1
  71. if os.path.isdir(file_path):
  72. print(f"错误:{file_path} 是一个目录,不是文件")
  73. return 1
  74. print(f"正在处理文件:{file_path}")
  75. print("将每一行的第二个字符移动到行首...")
  76. print("-" * 50)
  77. success = process_file(file_path)
  78. if not success:
  79. return 1
  80. return 0
  81. if __name__ == "__main__":
  82. exit(main())