views:

206

answers:

5

I want to write a python code that open a text file and Replace with a word that i want send to it . May you give me an example ? Thanks .

+1  A: 

There are so many ways to do this, but make sure you look at Template Strings to see if they're a good fit for your application.

From the documentation:

>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
[...]
ValueError: Invalid placeholder in string: line 1, col 10
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
[...]
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'
Stephen
that don't handle the file read and write!
Joschua
@Joschua : True. There are plenty of other answers that do that, I just thought the OP should be aware that there are modules built exactly for this use case.
Stephen
hmm ok, but I think it's a little bit inappropiate, to use a template "language" thingy for just replacing a word and saving it to a file.
Joschua
@Joschua : It's not inappropriate at all. Whether Eve should adopt this depends on what the use case is, her question didn't give enough background. That's why I said "look at template strings to see if they're a good fit for your application". If you are gonna replace _one_ word, then you probably want to replace _two_ words, and maybe _three_ words... pretty soon you're pissed because it accidentally substituted some stuff by accident and sent an email to a client. You're right - maybe it's overkill for what she wanted to do, but maybe not and it saves her a lot of time down the road.
Stephen
A: 

It can be as simple as this:

data = open('input_file').read()
open('output_file', 'w').write(data.replace('old_word', 'new_word'))

A cleaner version:

fh = open('input_file')
data = fh.read()
fh.close()

data = data.replace('old_word', 'new_word')

fh = open('output_file', 'w')
fh.write(data)
fh.close()
WoLpH
+1 for the clean version.
Steve
file is outdated. (http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files) and why to mention an unclean version? A beginner should learn it clean from the beginning.
Joschua
So, where exactly in your link does it suggest that `file` is outdated?
Steve
@Steve the example there uses `open(...)`. And use `Crtl + F`, search for `file(`. You will see, that there is none.
Joschua
@Joschua: I mention the unclean version to show that there are multiple options and to show how the Python syntax works. Also, I've replaced the `file` with `open`.
WoLpH
Joschua: Sorry, I thought you meant the `file` object, which wouldn't have made any sense.
Steve
A: 

Hello, you can do it this way using the with-statement:

PATH = "/home/Eva/test.txt"

with open(PATH) as f: # read the file content
    content = f.read()

with open(PATH, "w+") as f: # w+ stands for (re)write
    content = content.replace("abc", "test")
    f.write(content)

(abc is the old text, test the new text, which will replace old)

You can read more about files here. I hope that helps you.

Joschua
-1: Don't do that. The first line of code will destroy the file contents.
nosklo
Sorry, you're right. I missed that totally. (edited to work properly)
Joschua
still brewing trouble - the 1st time you opened the file, you did not close it explicitly and right after that you open it for writing. yes, file object will be closed when no longer in use but that is implementation specific and you risk the object might still be open while you try to open for writing
Nas Banov
I'm sorry and tired, but the file will be closed by the with (File-ContextManager). But I change it for you! ;)
Joschua
The `with` block should close the file.
detly
@detly the `with`-block always close the file at the end. (http://docs.python.org/reference/datamodel.html#context-managers)
Joschua
@nosklo will you remove -1?
Joschua
+2  A: 

surprised that MarteliBot has not replied yet :-) (i learned about fileinput from him here in some other thread) - so in a hurry, you can do the following:

import fileinput
for line in fileinput.input('somefile.txt', inplace=1):
    print line.replace('OldWord', 'NewWord'),

ps. this actually redirects stdout to the same file in a safe way (i.e. writes to tempfile and later renames etc). ain't it pretty?

Nas Banov
A: 
sed s/oldword/newword/g originalfile.txt > fixedfile.txt

:-)

Martin Thomas
You'll want to wrap that in a `subprocess.Popen` call.
detly