如何用Python批量将文件夹中TXT文件的非零索引转为零?
批量修改文件夹内TXT文件首列非零值为0的Python实现
实现思路
- 遍历目标文件夹下所有
.txt格式文件 - 逐行读取文件内容,拆分首列与剩余部分
- 若首列内容不为
0,则替换为0;为0则保持原样 - 将修改后的内容覆盖写入原文件(建议先备份文件)
代码实现
import os # 替换为你的目标文件夹路径 target_folder = "./your_txt_folder" for file_name in os.listdir(target_folder): if not file_name.endswith(".txt"): continue file_path = os.path.join(target_folder, file_name) updated_content = [] with open(file_path, "r", encoding="utf-8") as f: for line in f: cleaned_line = line.strip() if not cleaned_line: updated_content.append("") continue # 仅拆分首列和后续内容,保留原格式空格 if " " in cleaned_line: first_col, rest_content = cleaned_line.split(maxsplit=1) else: first_col, rest_content = cleaned_line, "" if first_col != "0": first_col = "0" # 拼接回原格式的行 updated_line = f"{first_col} {rest_content}".strip() updated_content.append(updated_line) # 写入修改后的内容 with open(file_path, "w", encoding="utf-8") as f: f.write("\n".join(updated_content) + "\n") print(f"处理完成: {file_name}")
关键说明
split(maxsplit=1):仅拆分首列与后续内容,避免破坏后续列的空格分隔格式- 空行处理:跳过空行,保持原文件的空行结构
- 编码设置:使用
utf-8编码读写,避免中文或特殊字符乱码 - 备份建议:执行前请务必备份目标文件夹内的所有文件,防止数据丢失
内容的提问来源于stack exchange,提问作者majioj
相关产品推荐
相关产品推荐

