Seite 1 von 1

stringproblem

Verfasst: Freitag 21. Juli 2006, 11:05
von rene04
hallo,

ich mag in einer datei bestimmte wörter ersetzen. also alle wörter wie web6 sollen durch web5 erstezt werden.habe dannmal folgendes gebastelt:

Code: Alles auswählen

#!/usr/bin/python2.4

import string

print 'dateioperation starten...'

myfile = open('/home/config.php', 'r+')
inhalt = myfile.read()

string.replace(inhalt, "web6", "web5")
#pos = string.find(inhalt, "../contenido/")

print inhalt

#myfile.write(inhalt)
leider tut sich da rein garnichts. was mache ich falsch??

Verfasst: Freitag 21. Juli 2006, 11:17
von icepacker
Hi
Probiers mal so:

Code: Alles auswählen

#!/usr/bin/python

print 'dateioperation starten...'

myfile = open('/home/config.php', 'r+')
inhalt = myfile.read()

neuer_inhalt = inhalt.replace("web6", "web5")
#pos = string.find(inhalt, "../contenido/")

print neuer_inhalt

#myfile.write(inhalt) 

Verfasst: Freitag 21. Juli 2006, 11:24
von rene04
hi,

danke das haut hin.

da hab ich die replace funktion wohl falsch verstanden.
replace( str, old, new[, maxreplace])

Return a copy of string str with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
deshalb hatte ich drei parameter :(
und ne zusätzliche variable hatte ich auch net, aber jetzt erscheint mir das logisch ;)

danke

gruesse rene

Verfasst: Freitag 21. Juli 2006, 11:36
von icepacker
Als Referenz empfehle ich die Online Documentation: http://docs.python.org/
Da gibts auch die aktuelle Funktionsweise von replace:
replace( old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Das string Modul musst du auch nicht mehr importieren, da sich (alle??)
string Verarbeitungen, als Methode des Objekts str aufrufen lassen!

Verfasst: Freitag 21. Juli 2006, 11:37
von rene04
noch jemand ne idee wie ich die ursprüngliche datei überschreibe anstatt dem krempel hintendrann zu hängen?

gruesse

Verfasst: Freitag 21. Juli 2006, 11:48
von icepacker
Da müsstest du mit 'r+' eigentlich schon richtig liegen.
Open for reading and writing; place the file pointer at the beginning of the file.

Verfasst: Freitag 21. Juli 2006, 11:49
von pr0stAta
Ein paar generelle Tips:

Hole dir Inhalt aus der Datei
Bearbeite den Inhalt
Schreibe den bearbeiteten Inhalt in eine neue Datei
Lösche die alte Datei und benenne die neue Datei um

So würde ich das angehen. Du kannst natürlich auch
erst aus der alten Datei lesen. Sie dann schließen und wieder
öffnen. Diesmal allerdings in einem anderen Modus. Also nicht r+
sondern w+.

prosta