Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python newbie: trying to create a script that opens a file and replaces words

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

like image 566
ziiweb Avatar asked Dec 03 '22 05:12

ziiweb


2 Answers

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'))
like image 118
Max Shawabkeh Avatar answered Dec 18 '22 13:12

Max Shawabkeh


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()
like image 38
Daniel G Avatar answered Dec 18 '22 15:12

Daniel G