英文:
replace a string with condition in python
问题
嗨,我正在尝试创建一个脚本,用于更改我的模型文件,并且我需要将文本字段类型更改为Bit1BooleanField,当字段类型是一个猜测时。我尝试了这个解决方案,但在替换第一个项目后一切都混乱了。
我的models.py示例:
class BaseCase(models.Model):
base_case_name = models.CharField(primary_key=True, max_length=255)
version = models.CharField(max_length=255)
default = Bit1BooleanField(blank=True, null=True) # 这个字段类型是一个猜测。
class ConfigApiMatrix(models.Model):
bloc = models.CharField(primary_key=True, max_length=255)
page = models.CharField(max_length=255)
activate_model_api = Bit1BooleanField(blank=True, null=True) # 这个字段类型是一个猜测。
module_api_break_point = Bit1BooleanField(blank=True, null=True)
first_api_to_run_after_save = Bit1BooleanField(blank=True, null=True)
我尝试的解决方案:
import re
with open('SFP/models.py', 'r') as myfile:
txt = myfile.read()
word = "Field(blank=True, null=True) # 这个字段类型是一个猜测."
for match in re.finditer(word, txt):
i = match.start()
txt = txt[:i-4-len(txt)] + "Bit1Boolean" + txt[i-len(txt):]
英文:
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):]
``
</details>
# 答案1
**得分**: 1
这应该是一个适合你的解决方案:
```python
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)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论