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

im trying to create a script that opens the file and replaces all "hola" with "hello".

f=open("kk.txt","w") for line in f: if "hola" in line: line=line.replace('hola','hello') f.close() 

But I get this error:

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

Any idea?

Xavi

+4
source share
4 answers

The main problem is that you first open the file for writing. When you open a file for writing, the contents of the file are deleted, making it difficult to take notes! If you want to replace the words in the file, you have a three-step process:

  • Read the file in line
  • Make a replacement on this line
  • Enter this line in 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() 
+4
source
 open('test.txt', 'w').write(open('test.txt', 'r').read().replace('hola', 'hello')) 

Or if you want to close the file correctly:

 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')) 
+7
source

You opened the file for writing, but you read it. Open the source file for reading and the new file for writing. After replacing, rename the original and the new one.

+4
source

You can also see with .

+3
source

Source: https://habr.com/ru/post/1306012/


All Articles