如何使用python将字符串插入到文本文件中?
这是我的文本文件如何使用python将字符串插入到文本文件中?,python,Python,这是我的文本文件 # This is an auto-generated Django model module created by ogrinspect. from django.contrib.gis.db import models class Parking(models.Model): name = models.CharField(max_length=80) descriptio = models.CharField(max_length=80) geo
# This is an auto-generated Django model module created by ogrinspect.
from django.contrib.gis.db import models
class Parking(models.Model):
name = models.CharField(max_length=80)
descriptio = models.CharField(max_length=80)
geom = models.PointField(srid=4326)
objects = models.GeoManager()
# Auto-generated `LayerMapping` dictionary for Parking model
parking_mapping = {
'name' : 'Name',
'descriptio' : 'Descriptio',
'geom' : 'POINT25D',
}
我想在
类停放(models.Model)之后插入层id=models.ForeignKey('sdr\u layer.id')
:
使用python脚本。可能吗?如何做?您可以先将所有内容读取到列表中,将文本插入所需位置(在这里可以使用正则表达式或“查找”/“索引”等),然后简单地重写文件。您可以先将所有内容读取到列表中,将文本插入所需位置(在这里可以使用正则表达式或“查找”/“索引”等)定位,然后简单地重写文件。您可以使用两种基本方法:
#!/usr/bin/python
filename='thefile.txt'
search="class Parking(models.Model):"
add="\n layer_id= models.ForeignKey('sdr_layer.id')"
content=open(filename,'r').read()
content=content.replace(search,search+add)
fp=open(filename,'w')
fp.write(content)
fp.close()
str.replace()
进行更改,然后将字符串写回文件,替换其中的内容第二种方法比较复杂,但会处理太大而无法放入内存的文件。您可以使用两种基本方法:
str.replace()
进行更改,然后将字符串写回文件,替换其中的内容