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','中国','日本')
  • 相关阅读:
    R中character和factor的as.integer的不同
    ggplot2练习
    R的plotmath
    Python数据科学手册(2) NumPy入门
    Python数据科学手册(1) IPython:超越Python
    ggplot2(6) 标度、坐标轴和图例
    R自带数据集
    ggplot2(5) 工具箱
    MATLAB神经网络(7) RBF网络的回归——非线性函数回归的实现
    ggplot2(4) 用图层构建图像
  • 原文地址:https://www.cnblogs.com/thanos-ryan/p/13288891.html
Copyright © 2011-2022 走看看