特定のファイルの個々の行を、行内の特定のキーワードを置き換えて上書きしようとしています。私はすでに複数の質問に目を通しており、答えのほとんどは私がすでに実装したものを示していました。 以下はコードです:あなたは、あなたが一度完成編集:)Pythonがファイルを上書きしない
finalText = "" # Here we will store the complete text
with open(fileLocation, "r") as openFile:
for line in openFile:
if line.strip().startswith("objectName:"):
line = ... # do whatever you want to do with the line.
finalText += line
をそのstrings
とwrite
テキストに変更を保存し、string
へのファイルのテキストを救うことができる
with open(fileLocation,"r+") as openFile:
for line in openFile:
if line.strip().startswith("objectName:"):
line = re.sub(initialName.replace(".qml",""),camelCaseName.replace(".qml",""),line)
print line
openFile.write(line)
openFile.close()
また、ここで間違っていることを説明してください。また、 'with'を使ってファイルを開いた場合、ファイルを明示的に閉じる必要はありません。 – BlackVegetable
置き換え中の行を上書きすることはできません。ファイルの内容は変わりません。 –
書き込みたいコンテンツがコンソールに正しく印刷されていますか?一見すると、このコードは実際にはそれらの行を置き換えずに、ファイルの末尾に追加されていると思います。 – BlackVegetable