Python - replace in place - delete backup .bak files using close () function?

When I run the following script, the backup .bak file remains on the file system. How to close () files correctly so that backups are deleted?

#!C:\Python27\python.exe
import os
myRelease = os.environ.get("BUILD_STRING")
myVersion = os.environ.get("VERSION_STRING")
import fileinput
import re
files = ["C:\Projects\FileToSub.sbs"]
for line in fileinput.FileInput(files,inplace=1):
   line = re.sub('whatever, thing', line)
   print line,

      

+3


source to share


2 answers


The module fileinput

takes care of deleting backup files.

I'm not really sure what you've tested, but your Python code is buggy. "Guess" and "fix" the version:

import fileinput
import re
files = ["FileToSub1.sbs", "FileToSub2.sbs"]
for line in fileinput.FileInput(files, inplace=1):
    line = re.sub('whatever', 'thing', line)
    print line,

      



In the strace output, you can see that the files are automatically deleted:

unlink("FileToSub2.sbs.bak")            = -1 ENOENT (No such file or directory)
rename("FileToSub2.sbs", "FileToSub2.sbs.bak") = 0
open("FileToSub2.sbs.bak", O_RDONLY)    = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=30, ...}) = 0
fstat(3, {st_mode=S_IFREG|0644, st_size=30, ...}) = 0
open("FileToSub2.sbs", O_WRONLY|O_CREAT|O_TRUNC, 0100644) = 4
fcntl(4, F_GETFL)                       = 0x8001 (flags O_WRONLY|O_LARGEFILE)
fstat(4, {st_mode=S_IFREG|0644, st_size=0, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fdf3a988000
lseek(4, 0, SEEK_CUR)                   = 0
fstat(4, {st_mode=S_IFREG|0644, st_size=0, ...}) = 0
chmod("FileToSub2.sbs", 0100644)        = 0
fstat(3, {st_mode=S_IFREG|0644, st_size=30, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fdf3a987000
read(3, "whatever\nfile\nthing\nline\nwhas\n", 8192) = 30
read(3, "", 4096)                       = 0
read(3, "", 8192)                       = 0
write(4, "thing\nfile\nthing\nline\nwhas\n", 27) = 27
close(4)                                = 0
munmap(0x7fdf3a988000, 4096)            = 0
close(3)                                = 0
munmap(0x7fdf3a987000, 4096)            = 0
unlink("FileToSub2.sbs.bak")            = 0

      

+1


source


you can call the close method like

myFile.close ()



Why don't you delete the file with os.remove ? You can do it:

import os

# call this after the end of your script
os.remove("C:\Projects\FileToSub.subs.bak")

      

+2


source







All Articles