Textdatei wird mehrfach beschrieben. Warum?

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
ramsy
User
Beiträge: 9
Registriert: Donnerstag 10. September 2015, 19:20

Hallo zusammen,

folgendes Szenario:
Ich lese die Werte einer Config Datei ein, suche in einer anderen Datei nach diesen Werten und ersetze durch jene, welche ich eingelesen habe. Bei diesem Prozess wird aber alles vier mal geschrieben. Ich kenne die Stelle wo das passiert, kann aber nicht verstehen warum. Vielleicht hat jemand einen Tip, was ich falsch mache:

Code: Alles auswählen

def changecs(Instances, *para_list):

    print 'INFO:: Opening ' + para_list[2]

    cspath = Instances + '/' + para_list[2]

    # OMSConnector.BCSAPHost_05 = X

    print "    :: Setting OMSConnector.LogFile to " + para_list[5]
    pattern_log = 'OMSConnector.LogFile='
    subst_log = 'OMSConnector.LogFile='+ para_list[5] + 'OMSConnector_' + para_list[0] + '.log'

    print "    :: Setting OMSConnector.ProtocolFile to " + para_list[2]
    pattern_protocol = 'OMSConnector.ProtocolFile='
    subst_protocol = 'OMSConnector.ProtocolFile='+ para_list[5] + 'OMSConnector_' + para_list[0] + '.prot'

    print "    :: Setting OMSConnector.WorkingDirectory to " + para_list[5]
    pattern_work = 'OMSConnector.WorkingDirectory='
    subst_work = 'OMSConnector.WorkingDirectory='+ para_list[5] + '/work'

    print "    :: Setting OMSConnector.DocumentDirectory to " + para_list[4]
    pattern_document = 'OMSConnector.DocumentDirectory='
    subst_document = 'OMSConnector.DocumentDirectory='+ para_list[4]


    fh, abs_path = tempfile.mkstemp()
    print "INFO:: Creating temp. working file"
    # open temp file with content of org. file
    with open(abs_path, 'w') as new_file:
        print "    :: Temp. working file created"
        with open(cspath) as old_file:
            # for every line in org file write in new file with replaced content
            #-------------------------
            # ICH DENKE HIER STIMMT WAS NICHT
            #
            for line in old_file:
                new_file.write(line.replace(pattern_log, subst_log))
                new_file.write(line.replace(pattern_protocol, subst_protocol))
                new_file.write(line.replace(pattern_work, subst_work))
                new_file.write(line.replace(pattern_document, subst_document))
                new_file.write(line.replace(pattern_document, subst_document))

        print "    :: Setting OMSConnector.LogFile to " + 'OMSConnector.LogFile=' + para_list[5] + 'OMSConnector_' + para_list[0] + '.log ... done'
        print "    :: Setting OMSConnector.ProtocolFile to " 'OMSConnector.ProtocolFile='+ para_list[5] + 'OMSConnector_' + para_list[0] + '.prot ... done'
        print "    :: Setting OMSConnector.WorkingDirectory to " + 'OMSConnector.WorkingDirectory='+ para_list[5] + '/work ... done'
        print "    :: Setting OMSConnector.DocumentDirectory to " + 'OMSConnector.DocumentDirectory='+ para_list[4] + ' ... done'
        print "    :: Closing file"
        print "    :: Moving files"

        os.close(fh)
        # Remove original file
        os.remove(cspath)
        # Move new file
        shutil.move(abs_path, cspath)
        print "    :: done"
    print 'INFO:: ' + cspath + ' changed successful'
Hat jemand eine Idee? Kann ich die For Schleife irgendwie anders aufbauen?

Danke euch
Zuletzt geändert von Anonymous am Donnerstag 11. August 2016, 19:57, insgesamt 1-mal geändert.
Grund: Quelltext in Python-Codebox-Tags gesetzt.
Sirius3
User
Beiträge: 17712
Registriert: Sonntag 21. Oktober 2012, 17:20

@ramsy: das stimmt nicht, alles wird 5 mal geschrieben, und zwar weil Du fünf `write`-Anweisungen geschrieben hast.

*-Argumente machen keinen Sinn, wenn man dann per magischer Indizes auf die Werte zugreift. Schreib die Parameternamen aus, dann ist auch gleich klar für was die da sind. Vermeide Abkürzungen. Was soll den das cs in changecs heißen? Als Programmierer will man sie eigentlich Schreibarbeit sparen. Bei vier Variablenpaaren, für die Du eigentlich das selbe machst, ist es besser eine passende Datenstruktur zu verwenden (hier habe ich mal ein Wörterbuch benutzt):

Code: Alles auswählen

def change_config(Instances, name, whatever1, filename, whatever2, document_directory, other_directory):
    filename = os.path.join(Instances, filename)
    params = {
        'OMSConnector.LogFile': os.path.join(other_directory, 'OMSConnector_{}.log'.format(name)),
        'OMSConnector.ProtocolFile': os.path.join(other_directory, 'OMSConnector_{}.proto'.format(name)),
        'OMSConnector.WorkingDirectory': os.path.join(other_directory, 'work'),
        'OMSConnector.DocumentDirectory': document_directory,
    }
    fh, abs_path = tempfile.mkstemp()
    with os.fdopen(fh, 'w') as new_file:
        with open(filename) as old_file:
            for line in old_file:
                for key, value in params:
                    line = line.replace(key + '=', key + '=' + value)
                new_file.write(line)
        shutil.move(abs_path, filename)
ramsy
User
Beiträge: 9
Registriert: Donnerstag 10. September 2015, 19:20

Hallo Sirius3,

danke für die Hilfe. Leider verstehe ich deinen Code noch nicht wirklich. Ich versuche Ihn mal zu analysieren und in mein Programm einzubauen.

Danke Dir.

Grüße
ramsy
ramsy
User
Beiträge: 9
Registriert: Donnerstag 10. September 2015, 19:20

Hallo Sirius3,

an dieser Stelle nochmal danke. Der Code funktioniert mit kleinen Anpassungen.

Hier meine ganze Lösung:

Code: Alles auswählen

def change_config(Instances, oms_name, config_directory, config_file, content_repository, import_path, oms_path):
    print 'INFO:: Opening ' +  config_file
    filename = os.path.join(Instances, config_file)
    print "    :: File opened"
    print "INFO:: Setting Paramaters"
    print "    :: Setting OMSConnector.LogFile"
    print "    :: Setting OMSConnector.ProtocolFile"
    print "    :: Setting OMSConnector.WorkingDirectory to"
    print "    :: Setting OMSConnector.DocumentDirectory to"

    params = {
        'OMSConnector.LogFile': os.path.join(oms_path, 'OMSConnector_%s.log'.format(oms_name)),
        'OMSConnector.ProtocolFile': os.path.join(oms_path, 'OMSConnector_%s.prot'.format(oms_name)),
        'OMSConnector.WorkingDirectory': os.path.join(oms_path, 'work'),
        'OMSConnector.DocumentDirectory': import_path,
    }
    print "    :: Parameters changed"
    print "INFO:: Writing File"
    fh, abs_path = tempfile.mkstemp()
    with os.fdopen(fh, 'w') as new_file:
        with open(filename) as old_file:
            for line in old_file:
                for key, value in params.iteritems():
                    line = line.replace(key + '=', key + '=' + value)
                new_file.write(line)
        shutil.move(abs_path, filename)
    print 'INFO:: ' + filename + ' changed successful'
Ich habe

Code: Alles auswählen

for key, value in params
noch auf

Code: Alles auswählen

for key, value in params.iteritems()
: gesetzt, da ich mit python 2.6 arbeiten muss. Weitere Infos dazu findet man http://stackoverflow.com/questions/3294 ... 99#3294899 . Vielleicht hilft es jemandem.
Antworten