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
2010-06-17 18:23:43
that don't handle the file read and write!
Joschua
2010-06-17 19:15:56
@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
2010-06-17 19:21:17
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
2010-06-17 20:09:26
@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
2010-06-17 20:32:08
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
2010-06-17 18:23:46
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
2010-06-17 18:32:28
@Steve the example there uses `open(...)`. And use `Crtl + F`, search for `file(`. You will see, that there is none.
Joschua
2010-06-17 20:02:54
@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
2010-06-17 21:59:09
Joschua: Sorry, I thought you meant the `file` object, which wouldn't have made any sense.
Steve
2010-06-18 02:00:29
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
2010-06-17 18:24:03
-1: Don't do that. The first line of code will destroy the file contents.
nosklo
2010-06-17 18:44:40
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
2010-06-17 20:15:03
I'm sorry and tired, but the file will be closed by the with (File-ContextManager). But I change it for you! ;)
Joschua
2010-06-17 22:03:27
@detly the `with`-block always close the file at the end. (http://docs.python.org/reference/datamodel.html#context-managers)
Joschua
2010-06-19 11:44:55
+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
2010-06-17 20:24:12