import os # 获取当前工作目录 current_dir = os.getcwd() # 遍历当前目录下的所有文件 for filename in os.listdir(current_dir): # 检查是否为 txt 文件 if filename.endswith('.txt'): filepath = os.path.join(current_dir, filename) # 读取文件内容并去掉换行符 try: with open(filepath, 'r', encoding='utf-8') as f: # 读取所有行,并用空字符连接,达到去掉换行符的效果 content = ''.join(line.strip() for line in f) # 写回原文件 with open(filepath, 'w', encoding='utf-8') as f: f.write(content) print(f'已处理: {filename}') except Exception as e: print(f'处理 {filename} 失败: {e}')