4

im trying to create a script that opens a file and replace every 'hola' with 'hello'.

f=open("kk.txt","w")

for line in f:
  if "hola" in line:
      line=line.replace('hola','hello')

f.close()

But im getting this error:

Traceback (most recent call last):
File "prueba.py", line 3, in for line in f: IOError: [Errno 9] Bad file descriptor

Any idea?

Javi

1
  • 1
    Why did you open the file with "w" mode? What tutorial are you using to learn Python?
    – S.Lott
    Apr 5, 2010 at 10:21

4 Answers 4

7
open('test.txt', 'w').write(open('test.txt', 'r').read().replace('hola', 'hello'))

Or if you want to properly close the file:

with open('test.txt', 'r') as src:
    src_text = src.read()

with open('test.txt', 'w') as dst:
    dst.write(src_text.replace('hola', 'hello'))
3
  • 1
    True, but for a beginner, this is the most simple and straightforward way. Apr 5, 2010 at 9:42
  • 1
    Answer shadows 'input' built-in, maybe src_text might be a better variable name?
    – PaulMcG
    Apr 5, 2010 at 13:49
  • @Paul: Might as well. Edited. Apr 5, 2010 at 15:36
4

Your main issue is that you're opening the file for writing first. When you open a file for writing, the contents of the file are deleted, which makes it quite difficult to do replacements! If you want to replace words in the file, you have a three-step process:

  1. Read the file into a string
  2. Make replacements in that string
  3. Write that string to the file

In code:

# open for reading first since we need to get the text out
f = open('kk.txt','r')
# step 1
data = f.read()
# step 2
data = data.replace("hola", "hello")
f.close()
# *now* open for writing
f = open('kk.txt', 'w')
# step 3
f.write(data)
f.close()
3
  • We should teach beginners to use 'with' from the start - see Max Shawabkeh's answer.
    – PaulMcG
    Apr 5, 2010 at 13:48
  • @paul I don't disagree; however, since the user was already having difficulty with the concept of manipulating files, I originally decided to keep my answer as close to his original code as possible. Since a subsequent question by the user indicated Python 2.5 (which requires a special import from the __future__), I figured I might as well not change it. The other answer is, of course, equally correct if not as explicit.
    – Daniel G
    Apr 5, 2010 at 16:20
  • And beware that simple replace will a) not match "Hola" and give "Hello", and b) will match 'hola' in 'scholar' giving 'schellor'.
    – PaulMcG
    Apr 5, 2010 at 17:49
4

You've opened the file for writing, but you're reading from it. Open the original file for reading and a new file for writing. After the replacement, rename the original out and the new one in.

3

You could also have a look at the with statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.