replace a string with condition in python

Question:

hi all i’m trying to create script that makes changes to my models file and i need it to change the textfield type to Bit1BooleanField when the field type is a guess
i tried this sultion but after replacing the first item everything is missed up

my models.py sample:

class BaseCase(models.Model):
    base_case_name = models.CharField(primary_key=True, max_length=255)
    version = models.CharField(max_length=255)
    default = TextField(blank=True, null=True)  # This field type is a guess.


class ConfigApiMatrix(models.Model):
    bloc = models.CharField(primary_key=True, max_length=255)
    page = models.CharField(max_length=255)
    activate_model_api = models.TextField(blank=True, null=True)  # This field type is a guess.
    module_api_break_point = models.TextField(blank=True, null=True)
    first_api_to_run_after_save = models.TextField(blank=True, null=True)

the solution i tried:

import re

with open('SFP/models.py', 'r') as myfile:
  txt = myfile.read()

word = "Field(blank=True, null=True)  # This field type is a guess."
for match in re.finditer(word, txt):
    i=match.start()
    txt = txt[:i-4-len(txt)] + "Bit1Boolean" + txt[i-len(txt):]
``

Asked By: Mehdi Selbi

||

Answers:

This should be a solution for you

search = 'TextField(blank=True, null=True)  # This field type is a guess.'
replace = 'Bit1BooleanField(blank=True, null=True)  # This field type is a guess.'

with open('SFP/models.py', "r") as f:
  txt = f.read()
  replaced_data = txt.replace(search, replace)
with open('SFP/models.py', "w") as f:
  f.write(replaced_data)
Answered By: weAreStarsDust