python txt内容批量处理

img


一共20万行,将i*20+16 17 18 19这4万行修改为五个0,间隔三个空格

可以读取数据文件所有行后,再循环遍历每一行,当是指定行数数据时,则用5个0来代替,其他行正常复制。

下面的代码,先产生了20万行的测试数据文件,然后再读取这个文件内容,把指定行数的数据用5个0代替,其他行正常复制,都写入到另一个文件。

测试代码如下:

参考链接:


https://blog.csdn.net/m0_72893325/article/details/129533250

https://www.zhangshilong.cn/work/232672.html

https://www.ycpai.cn/python/TkKfBw67.html

https://blog.csdn.net/i1024i/article/details/129519066



import random

# https://blog.csdn.net/qq_44732742/article/details/124506009
#  第一部分,  用于产生20万行的测试数据,如果已经有数据,则可以去除此部分代码
with open("datas0331.txt","w") as file:
    
    for j in range(200000):
        for i in range(5):
            # https://blog.csdn.net/m0_72893325/article/details/129533250
            # https://www.zhangshilong.cn/work/232672.html
            data = round(random.uniform(100,65536),2)
            file.write(str(data))
            if i< 4:
                file.write("   ")
            if i==4 and j!=199999:
                file.write("\n")

# 第二部分,执行数据文件替换,然后把数据写入另一个文件,如果已经有数据文件,只需要部分代码
# https://www.ycpai.cn/python/TkKfBw67.html
resultFile= open("datas0331Result.txt","w")# 把修改后的数据写入另一个文件

i=1  # 从第一行开始   
with open("datas0331.txt","r") as readFile: # 打开测试数据文件,读取数据

    # https://blog.csdn.net/i1024i/article/details/129519066
    for line in readFile.readlines(): # 遍历测试文件的每一行
         # 当是指定行数的数据时,用5个0来代替这一行
        if ((i-16)%20==0 or  (i-17)%20==0 or (i-18)%20==0 or (i-19)%20==0 )and i>=36:
            resultFile.write("0   0   0   0   0\n")   
        else: # 其他行原样复制
            resultFile.write(line)
        i=i+1 
       
resultFile.close()        
      

img

试试用这个手动完成:
TSEPro11_Setup.exe 百万军中取上将首级如探囊取物, 千万行里改关键源码在弹指瞬间。 功能超强的程序编辑器! https://blog.csdn.net/zhao4zhong1/article/details/126596717 https://bbs.csdn.net/forums/tsepro11 https://gitcode.net/zhao4zhong1/tsepro11 https://gitee.com/zhao4zhong1/tsepro11/raw/master/TSEPro11_Setup.exe