zoukankan      html  css  js  c++  java
  • 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+'
    ')
        os.replace(changed_file,file)
    modify_file('news','中国','日本')
  • 相关阅读:
    [转载]C#.NET中Dns类的常用方法及说明
    [转载]如何辨别真假百度蜘蛛
    Lottie的json动画
    iOT
    iOS字体大小
    针对Xcode 9 + iOS11 的修改,及iPhone X的适配
    shell脚本之 给PNG图片添加后缀@3x
    正则表达式
    CSS
    XcodeProj,使用Ruby更改工程文件
  • 原文地址:https://www.cnblogs.com/thanos-ryan/p/13288891.html
Copyright © 2011-2022 走看看