3

当我运行以下脚本时,文件系统中会留下一个 .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,
4

2 回答 2

2

你可以调用close方法,例如

我的文件.close()

为什么不使用os.remove删除文件?你可以这样做:

import os

# call this after the end of your script
os.remove("C:\Projects\FileToSub.subs.bak")
于 2012-04-04T10:11:20.997 回答
1

fileinput模块负责删除备份文件。

我不完全确定你测试了什么,但你的 python 代码包含错误。一个“猜测”和“更正”的版本:

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
于 2012-04-04T10:28:56.207 回答