How to insert a string of characters into a text file using python?
This is the text file I have . 开发者_StackOverflow社区
# 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',
}
I want to insert layer_id= models.ForeignKey('sdr_layer.id')
after class Parking(models.Model):
using python script . Is it possible ? How to do it ?
#!/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()
You can first read all into a list, insert your text into the required(here you can use regular expressions or 'find'/'index' and etc) position and then simply rewrite file.
There are two basic approaches you can use:
Read the whole file into memory as a single string, make the change using a regular expression or just
str.replace()
, and then write the string back out to the file, replacing what was in it.Read the file line by line, copying lines to a new file, until you reach the place where you want to add the line. At this point, write the new line to the new file. Then copy the rest of the lines to the new file. When done, rename the new file so it replaces the existing one.
The second one is more complicated but will work with files too large to fit into memory.
精彩评论