Ich möchte eine Datei schreiben und dann ändern, indem Sie einen anderen Inhalt an den Anfang und das Ende der Datei einfügen.Wie füge ich Inhalt am Anfang der Textdatei ein?
Mein Code:
f = open('Blowing in the wind.txt', 'w+')
f.seek(0)
f.truncate()
f.write('''
How many roads must a man walk down
Before they call him a man
How many seas must a white dove sail
Before she sleeps in the sand
''')
content= f.read()
f.seek(0)
f.write('Blowing in the wind\n' + 'Bob\n'+content)
f.seek(0,2)
f.write('\n1962 by Warner Bros.Inc.')
f.seek(0,0)
txt= f.read()
print(txt)
Ergebnis:
Blowing in the wind
Bob
n walk down
Before they call him a man
How many seas must a white dove sail
Before she sleeps in the sand
1962 by Warner Bros.Inc.
Wie der zusätzlichen Inhalt überschreibt die erste Zeile im ursprünglichen Text zu verhindern?
Kontrolle dieser [post] (https://stackoverflow.com/questions/5914627/prepend-line-to-beginning-of-a-file) – PRMoureu