1.删除txt文件中的空格
2.如果顶行是空格,把这一行的数据更换成 空格+空格+O
import os; #待读取文件夹地址,存放多个待读取的txt文件 read_path = "D:\\read\\"; #存放生成的txt文件的文件夹地址 write_path = "D:\\write\\"; for path in os.listdir(read_path): f = open(read_path + path, "r", encoding='utf-8') with open(write_path + path, "w", encoding='utf-8') as fn: lines = f.readlines() for line in lines: if line != "\n": if line.startswith(' '): fn.write(' O\n'); else: fn.write(line);