import os src = 'stock_data.txt' dst = 'bak' with open('stock_data.txt','r',encoding='utf-8') as file_1 , open('bak','w',encoding='utf-8') as file_2: while 1: f_1 = file_1.readline() for i in f_1: if '亿' in i: f_1 = f_1.replace('亿','00000000') if f_1: file_2.write(f_1) else: break # os.remove(src) #os.rename(dst, src) os.replace(dst, src)
自定义参数
python *.py src dst
# -*- encoding: utf-8 -*- import os import sys argvs = sys.argv src = argvs[1] dst = argvs[-1] with open(src,'r',encoding='utf-8') as file_1 , open(dst,'w',encoding='utf-8') as file_2: while 1: f_1 = file_1.readline() for i in f_1: if '0' in i: f_1 = f_1.replace('0','*') if f_1: file_2.write(f_1) else: break # os.remove(src) #os.rename(dst, src) os.replace(dst, src)
python读取文件优化(附加编码及解码,编码与解码要一致):
利用文件句柄迭代取值,节省内存空间
with open('test.txt','r',encoding='gbk') as file: for i in file: print(i.encode('utf-8').decode('utf-8'))
修改整个文件内的所有内容:
import os def modify_file(file,content,content_changed): changed_file = '%s.bak' % file with open(file,'r',encoding='utf-8') as f_1 ,open(changed_file,'w',encoding='utf-8') as f_2: for i in f_1: i = i.strip() if content in i: i = i.replace(content,content_changed) f_2.write(i+' ') os.replace(changed_file,file) modify_file('news','中国','日本')