Pregunta

I'm trying to replace text in a .txt file using a .py script. Here's what i have so far:

docname=raw_input("Enter a document name: ")    
fo=open(docname, 'r+')    
string=fo.read()    
replace=raw_input("Enter what you want to replace: ")    
replacewith=raw_input("Enter what you want to replace it with: ")    
out=string.replace(replace,replacewith)    
fo.write(out);    
fo.close()    
print "Check the document!"    
closeInput = raw_input("Press ENTER to exit")

I have a txt file called "test.txt" (in the same directory as the .py script). When I enter "test.txt", it asks what I want to replace, as expected. When I fill out that, it asks for what I want to replace it with.

I fill out that, and the program closes. No "Check the document!" or anything. And worst of all, it doesn't replace it with the second string.

Please help!

¿Fue útil?

Solución

you have 2 possibilities:

  1. if you want to open the file just once, you should reset the position of the stream with fo.seek(0)
  2. you can close and reopen the file with fo = open(docname, 'w')

The first option has one problem: if the replace-text is shorter than the original-text, some text will be left over at the end. To illustrate what I'm talking of: You have the text '12345' and want to replace '12' with 'a', then the resulting file would contain 'a3455'

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top