[Tutor] Python help!!

Alan Gauld alan.gauld at btinternet.com
Tue Apr 2 19:48:44 CEST 2013


On 02/04/13 17:49, David Mitchell wrote:

> How do I go through a text file, finding specific words/numbers/phrases
> and edit them to say different things? I do not want to edit the text
> file, I would rather open and read from the text file and write to a new
> file.

OK That's easy, you just write the old file to the new file with the 
changes in place.

> I do NOT want to know how to replace a specific word with another every
> time it appears. There are some "OFF" 's that i would like to change to
> "ON" 's and some that I would like to change to "OPEN" for example.

OK so, instead of calling replace, you want to stop and ask the user for 
a replacement text? Is that the idea?

> I am doing all this in Linux Fedora with gedit.

I don't know gedit but both vim and emacs have interactive
replacement functions, maybe gedit has too. Both vi and
emacs can create macros and you can auto run macros when
you start the editor, so you could automate it all
using those tools.

But Python can work almost as easily (and probably the
finished article will be faster)

> Any help would be greatly appreciated!!

Why don't you tell us how you think it should work?
Its likely that all the bits you need are already
available to you with a little thought. Research
the string methods (and if you want to get (too) clever
the re module too).

(I'm assuming these files are short enough to read them
all into memory as a single string? If not we need to
get slightly smarter.)

Try a solution and tell us where you get stuck.
Even pseudo code if you aren't confident with
real Python.

If that's too hard at least try to produce a hypothetical
user session showing us what you expect the program
to look like in use.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list