I would like to parse a file line by line and replace a fixed punctuation with another punctuation (e.g. periods "/" with slashes ".") Only if that string in the line contains a certain variable
Example: Replace only if the string contains Fx
line1: test1/test2
line2: .test + e/y + Fx/var1/var2
Output:
line1: test1/test2
line2: .test + e/y + Fx.var1.var2
How can I go about doing this? Code so far but I know it doesn't work
import os
textToFind = '/'
textToReplace = '.'
sourcepath = os.listdir('InputFiles/')
def lines_that_contain(string, fp):
return [line for line in fp if string in line]
for file in sourcepath:
inputFile = 'InputFiles/'+ file
print('Conversion is ongoing for:' +inputFile)
with open(inputFile, 'r') as inputFile:
for line in lines_that_contain("Fx.", inputFile):
print('found Fx.')
fileData = fileData.replace(textToFind, textToReplace)
freq2 = 0
freq2 = fileData.count(textToFind)
destinationPath = 'OutputFile/' + file
with open(destinationPath, 'w') as file:
file.write(fileData)
print ('Total %d Record Replaced' %freq2)
else:
print('Did not find selected strings')