Editing particular lines of a text file.

Tim Williams tdwdotnet at gmail.com
Tue Oct 9 13:38:02 CEST 2007


On 09/10/2007, Shriphani <shriphanip at gmail.com> wrote:
> Hello all,
>
> I am trying to create a script that looks at specific strings in a
> file like:
>
> msgid "I am a disco dancer."
>
> and compares the part in quotes to the keys in a dictionary, finds the
> value and creates a new line right after this string in the file. I
> have planned to write this as follows:
>
> 1. Open the file in read mode
> 2. parse each line to figure out which line contains "msgid" and use
> the shlex module's split method to go and split this line and pick the
> 2nd element list[1].
> 3. find the value from the dictionary corresponding to the above
> element.
> 4. Insert the line. This part is where I face a problem. How do I
> plainly edit just one line. I would also like to look at some sample
> code that does this.
> 5. open a new file and write the new file with the inserted strings to
> it.
> 6. close both files opened.


infile = open('infile.txt')
outfile = open('outfile.txt','w')
for line in infile:
    if 'msgid' in line:
         #  transform line
         #  make sure the line ending is intact
    outfile.write(line)
infile.close()
outfile.close()

or maybe

infile = open('infile.txt')
outfile = open('outfile.txt','w')
new_file = []
for line in infile:
    if 'msgid' in line:
         #  transform line
         #  make sure the line ending is intact
    new_file.append(line)
outfile.write(''.join(new_file)
infile.close()
outfile.close()




-- 

Tim Williams



More information about the Python-list mailing list