[Tutor] Editing files through Python

Alan Gauld alan.gauld at blueyonder.co.uk
Tue Aug 31 00:15:12 CEST 2004


> How do I delete, cut, or paste portions of the data I am
> reading and how do I tell the program to jump to that
> specific portion of data that I want to alter?

Ok, to some extent you need to stop thinking like a word processor
and think more like a computer! :-)

> I have two rows of numbers, as shown below.  Each row has 10 numbers
>
> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
> 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
>
> What commands might I use to automatically go through each row,
> deleting the 6th through 10th numbers in each row

you want to process each line in the file so you need a for loop.

for line in myfile:

That gets line pointing to a long string of characers, which you
need to split using the spaces,

    items = line.split()

items now is a list of your numbers with the spaces but without
the commas.

Lets make it more challenging by deleting the 6th-9th inclusivew
- ie we keep the last number. We can use list slicing to select
out the bits we want or we can use another for loop. The loop
approach is more general so I'll show that:

items2 = []
for index in range(len(items)):
    if not (5 <= index < 9):
       items2.append(items[index])


We could make that more flexible by creating a function which has
lower and upper bounds as parameters.

We could also have used a list comprehension:

items2 = [items[i] for i in range(len(items)) if not (5 <= i < 9)]

Now you just need to reconstruct the line ready to write it out
again:

line = ' '.join(items2)
newfile.write(line + '\n')

Put all the pieces together and you should find it works - or very
nearly! :-)

HTH

Alan G.



More information about the Tutor mailing list