Skip to main content

Replace_character

I show here how to remove a certain character from set of lines in a text file using Python

In [1]:
import numpy as np

Here I am reading each line and removing the character '%'

In [ ]:
F =open(path+'textfile1.txt','r')
F2 = open(path+'textfile2.txt','w')

for line in F:
    line = line.split('%')[0]
    F2.write(line+'\n')
F2.close()

Here I am removing the same character and replacing a comma in a decimal by a point

In [ ]:
F =open(path+'textfile1.txt','r')
F2 = open(path+'textfile2.txt','w')

for line in F:
     l = []
     
    
     line = line.split('%')[0]
    
     for n in range(len(line.split())):
        l.append(line.split()[n].replace(',','.'))
        
     l = ' '.join(l)
        
     F2.write(l+'\n') #to convert list to str (https://www.decalage.info/en/python/print_list)
F2.close()