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