RedGlyphの提案によれば、Windows APIにアクセスするためにctypesを使用するReplaceFileの実装が追加されています。私は最初これをjaraco.windows.api.filesystemに追加しました。
ReplaceFile = windll.kernel32.ReplaceFileW
ReplaceFile.restype = BOOL
ReplaceFile.argtypes = [
LPWSTR,
LPWSTR,
LPWSTR,
DWORD,
LPVOID,
LPVOID,
]
REPLACEFILE_WRITE_THROUGH = 0x1
REPLACEFILE_IGNORE_MERGE_ERRORS = 0x2
REPLACEFILE_IGNORE_ACL_ERRORS = 0x4
次に、このスクリプトを使用して動作をテストしました。
from jaraco.windows.api.filesystem import ReplaceFile
import os
open('orig-file', 'w').write('some content')
open('replacing-file', 'w').write('new content')
ReplaceFile('orig-file', 'replacing-file', 'orig-backup', 0, 0, 0)
assert open('orig-file').read() == 'new content'
assert open('orig-backup').read() == 'some content'
assert not os.path.exists('replacing-file')
これはWindowsでのみ機能しますが、他の置換ルーチンにはない素晴らしい機能がたくさんあるようです。詳細は、API docsを参照してください。あなたは改行のを書くことができます前に、全体の内容を読み込む必要がある場合は、その後、
import fileinput
for line in fileinput.input(filename,inplace=True, backup='.bak'):
# inplace=True causes the original file to be moved to a backup
# standard output is redirected to the original file.
# backup='.bak' specifies the extension for the backup file.
# manipulate line
newline=process(line)
print(newline)
を:
なぜコピーしますか?なぜ名前を変更しないのですか? –