python对文档删除和替换
心之所向521 人气:0pthon更换文档中某元素:
with open('E:\\桌面\\train.txt', 'r') as f: lines = f.readlines() with open('E:\\桌面\\1704.txt', 'a') as ff: # 此处 w 和 a,均可,反正是新建的临时文件,文件不存在时会自动创建 for line in lines: # kv = line.strip().split(' ') kv = line.split(' ') # kv[2] = kv[2]*100 m = float(kv[2]) m = round(m * 100, 1) if kv[2]: line = line.replace(kv[2], str(m)) ff.write(line) # shutil.move('123.yml', 'apktool.yml')
python改变或者删除txt文档中某一列元素
##改变或者删除txt文档中某一列 import re with open('E:\\桌面\\train.txt', 'r') as f: ##最开始要改变的文档 lines = f.readlines() # for line in lines: # line = re.split(' | ', line) # print(line) l = [] for line in lines: # kv = line.strip().split(' ') kv = line.strip(" ").split(' ') kv.pop(3) kv.pop(3) # print(kv) l.append(kv) # print(l) with open('E:\\桌面\\1706.txt', 'a') as ff: # 此处 w 和 a,均可,反正是新建的临时文件,文件不存在时会自动创建 for i in l: print(i) for i1 in i: ff.write(i1) # 写入 ff.write(' ') # 有时放在循环里面需要自动转行,不然会覆盖上一条数据 ff.close() with open('E:\\桌面\\1706.txt', 'r') as fff: ##读取临时文档 lines1 = fff.readlines() with open('E:\\桌面\\1707.txt', 'a') as ffff: ###创建最后的要求的文档 for line in lines1: i2 = line.strip(" ").split(' ') n = float(i2[2]) m = round(n * 100, 1) line = line.replace(i2[2], str(m)) ffff.write(line) # # line = i.replace(i[2], str(m)) # print(line) # ff.write(line) # for line in lines: # # kv = line.strip().split(' ') # kv = line.split(' ') # kv.pop(3) # kv.pop(4) # # print(kv) # l.append(kv) # print(l) # # # # m = float(kv[2]) # # m = round(m * 100, 1) # # print(kv) # # line = line.replace(kv[2], str(m)) # # print(line) # # # line = line.replace(kv[3], '', 1) # # # line = line.replace(kv[4], '', 1) # # ff.write(line) # #
加载全部内容