2012-04-04 56 views
3

當我運行以下腳本時,.bak備份文件留在文件系統中。 如何正確關閉()文件以便備份被刪除?Python - 替代inplace - 使用close()刪除.bak備份文件?

#!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, 

回答

1

fileinput模塊負責刪除備份文件。

我不完全確定你測試了什麼,但是你的python代碼包含錯誤。 A '猜' 和 '糾正' 版本:

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, 

在strace的輸出,你可以看到,這些文件會被自動刪除:

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 
+0

確實很奇怪:) – Dikei 2012-04-04 10:30:06

+0

但是備份文件對我來說依然存在! 也許是因爲我在jenkins中運行python腳本? – shanz 2012-04-04 10:30:31

+0

你可以將'strace'輸出添加到問題中嗎? – 2012-04-04 10:31:29

2

您可以調用close方法,例如,

myfile.close()

你爲什麼不刪除使用os.remove文件?你可以這樣做:

import os 

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

目前... 進口統計 os.chmod( 「C:\ Projects \ FileToSub.sbs.bak」,stat.S_IWRITE) os.remove(「C:\ Projects \ FileToSub.sbs.bak」)' 似乎要做這項工作,但感覺不對。 – shanz 2012-04-04 11:00:15

+0

也許Andreas Florath更接近你想要的東西。看到我的評論給他的答案! – 2012-04-04 11:04:44

相關問題