Home > Software design >  How to remove specific text from file
How to remove specific text from file

Time:05-07

I have a file containing text like

0 de is 1568.1612302738604
1 de is 553.203055894161
2 de is 1593.492544682082
3 de is 1583.9043943157742
4 de is 1575.9076019892175
5 de is 1485.8005089881244
6 de is 988.1260339774907

I need to remove the first string from the text and remains numbers after de is to be like that

1568.1612302738604
553.203055894161
1593.492544682082
1583.9043943157742
1575.9076019892175
1485.8005089881244
988.1260339774907

the code i tried is

import os

inputFile = open("file1", "r")
exportFile = open("file2", "w")

i = 0
for line in inputFile:
    new_line= line.replace(str(i) " de is ",'')
    exportFile.write(new_line) 
    i =1

exportFile.close()    

but didn't work

CodePudding user response:

You could use regex for this

import re

key, your_decimal_number = re.findall('\d*\.?\d ',line)

index is 0 your decimal number is '1568.1612302738604'

if you do not need index you can use re.findall("\d \.\d ", line) keep that in mind re.findall returns a list

CodePudding user response:

lst = []
with open('test.txt') as f:
    for line in f:
        lst.append(line.split('de is ')[-1])

with open('test.txt','w') as f:
    f.writelines(lst)
  • Related