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(开发者_如何学Python)
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
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'))
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:
- Read the file into a string
- Make replacements in that string
- 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()
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.
You could also have a look at the with statement.
精彩评论