somepeople

python文件实时修改文件并读取

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+'\n')
    os.replace(changed_file,file)
modify_file('news','中国','日本')

 过滤,没有才追加

def check_char(file,char):
    with open(file,'r',encoding='utf-8') as file_1, open(file,'r+',encoding='utf-8') as file_2:
        for i in file_1:
            if i.__contains__(char):
                print('%s exists'%char)
                break
        else:
            file_2.seek(0,2)
            file_2.write('\n%s'%char)
check_char('username','alex')

 过滤,有就删除

import os
def clean(file,id):
    user_list=[]
    with open(file,'r',encoding='utf-8') as file_1:
        for i in file_1:
            user_list.append(i)

    for i in user_list:
        if i.split(',')[-1] == '%s\n'%id:
            user_list.remove(i)
    with open('%s.bak' % file, 'w', encoding='utf-8') as file_2:
        for i in user_list:
            file_2.write(i)
    os.replace('%s.bak'%file,file)
clean('username',100001)

 

posted on 2020-07-12 16:41  Hello_Thanos  阅读(848)  评论(0编辑  收藏  举报

导航