zoukankan      html  css  js  c++  java
  • python练习六十二:文件处理,往文件中所有添加指定的前缀

    往文件中所有添加指定的前缀

    方法一:open方法

    f_r = open('text.txt')
    f_w = open('text_new.txt','w+')
    i = 0
    while True:
        i += 1
        line = f_r.readline()
        if not line:
            break
        f_w.write('%02d'%i + '.python'+ ' ' +line)
    f_r.close()
    f_w.close()
    f_wr = open('text_new.txt','r')
    lines = f_wr.readlines()
    for i in lines:
        print(i)
    f_wr.close()
    方法二:with open方法

    with open('text.txt') as f_r:
         line = f_r.readline()
         with open('text_new.txt','w') as f_w:
             i = 0
             while True:
                 i += 1
                 line = f_r.readline()
                 if not line:
                     break
    #             f_w.write('%02d'%i + '.python'+ ' 'len+line)  #格式化输出方法一
                 f_w.write('{:>2}{}{}{}'.format(i,'.python',' ',line)) #格式化输出方法二

    with open('text_new.txt','r') as f_wr:
         lines = f_wr.readlines()
         for i in lines:
             print(i)

    执行结果:

    01.python jave
    02.python go
    03.python shell
    04.python perl
  • 相关阅读:
    高速传输线PCB设计
    带状线和微带线
    资源分配
    异步时钟切换电路
    Mathcad操作tips:2D绘图
    Mathcad操作tips:函数、符号计算
    慢性胃炎注意事项
    Arduino I2C + 三轴加速度计ADXL345
    Arduino SPI + SPI Flash芯片W25Q80BV
    Arduino I2C + 三轴加速度计LIS3DH
  • 原文地址:https://www.cnblogs.com/pinpin/p/10299903.html
Copyright © 2011-2022 走看看