在python中用条件替换字符串

在python中用条件替换字符串,python,string,django-models,Python,String,Django Models,大家好,我正在尝试创建一个脚本来更改我的模型文件,当字段类型是猜测时,我需要它将textfield类型更改为Bit1BooleanField 我试过这个结果,但在更换第一件物品后,所有东西都丢失了 my models.py示例: 类基本情况(models.Model): 基本大小写名称=models.CharField(主键=True,最大长度=255) version=models.CharField(最大长度=255) default=TextField(blank=True,null=Tr

大家好,我正在尝试创建一个脚本来更改我的模型文件,当字段类型是猜测时,我需要它将textfield类型更改为Bit1BooleanField 我试过这个结果,但在更换第一件物品后,所有东西都丢失了

my models.py示例:

类基本情况(models.Model):
基本大小写名称=models.CharField(主键=True,最大长度=255)
version=models.CharField(最大长度=255)
default=TextField(blank=True,null=True)#此字段类型是猜测。
类ConfigApiMatrix(models.Model):
bloc=models.CharField(主键=True,最大长度=255)
page=models.CharField(最大长度=255)
激活_model_api=models.TextField(blank=True,null=True)#此字段类型是猜测。
模块\ api \断点\点=models.TextField(blank=True,null=True)
在保存=models.TextField(blank=True,null=True)之后运行的第一个api
我尝试的解决方案是:

重新导入
以open('SFP/models.py','r')作为myfile:
txt=myfile.read()
word=“Field\(blank=True,null=True\)#此字段类型是一种猜测。”
对于re.finditer(word,txt)中的匹配:
i=match.start()
txt=txt[:i-4-len(txt)]+“Bit1Boolean”+txt[i-len(txt):]
``

这应该是您的解决方案

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)