删除Python中的文件不起作用

Dan*_*Dan 0 python python-2.7

我正在尝试使用以下命令删除临时文件:

os.remove(str('temp.bin'))
Run Code Online (Sandbox Code Playgroud)

这是完整的功能,请注意我使用API​​(XWF)将数据读出到文件中,这样可以正常工作.这在收到有效图像时工作正常,因此问题不在此结束之外.代码仅在收到无效的图像文件时才会出现问题.我读取了临时文件的输入,因为它适用于我的解决方案,这里的问题是当它们不是有效图像时它不会删除它们.我不是在寻找一个关于为什么在将它写入临时文件之前检测它是否是图像会更好的讲座.幽默我,现在假设我有充分的理由这样做.

import OutputRedirector
import XWF
import os
from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS

gps_data = {}

def XT_ProcessItemEx(nItem, hItem, reserved):
    global gps_data
    fn = XWF.GetItemName(nItem)
    offset = 0
    size = XWF.GetItemSize(nItem)
    if offset < size:
        tempfn = fn + '.bin'
        f = open(tempfn, 'wb')
        buffer = XWF.Read(hItem, offset, size)
        f.write(buffer)
        f.close()
        try:
            image = Image.open(tempfn)
            exif_data = get_exif_data(image)
            gps = get_lat_lon(exif_data)
            if gps[0]:
                gps_data[fn] = (repr(gps[0]), repr(gps[1]))
                print('Found GPS data in %s' % fn)
            else:
                print('No GPS data in image %s' % fn)
            del image
            os.remove(str(tempfn)) # it works fine here
        except IOError:
            print('Not an image')
            os.remove(str(f)) # but it won't work here
    else:
        print('File too small')
    return
Run Code Online (Sandbox Code Playgroud)

如果我不按原样保留该行并且不使用str()机箱,则会出现此错误:

TypeError :  must be string, not file 
Run Code Online (Sandbox Code Playgroud)

因为我得到这个错误:

WindowsError :  [Error 123] The filename, directory name, or volume 
label syntax is incorrect: "<closed file u'file.pdf.bin', 
mode 'wb' at 0x0A82A0D0>" 
Run Code Online (Sandbox Code Playgroud)

如果我在函数/方法根级别返回之前直接移动违规行,我会收到以下错误:

WindowsError :  [Error 32] The process cannot access the file because 
it is being used by another process
Run Code Online (Sandbox Code Playgroud)

我不确定为什么它适用于图像但不适用于f.

Mar*_*ers 7

您正在尝试使用文件对象,而不是文件名.使用os.remove(f.name)或使用os.remove(tmpfn).

您还希望切换到使用文件作为上下文管理器(使用该with语句),以便它们自动关闭,并且您也可能对该tempfile模块感兴趣.

使用with:

with open(tempfn, 'wb') as f:
    buffer = XWF.Read(hItem, offset, size)
    f.write(buffer)
Run Code Online (Sandbox Code Playgroud)

(请注意f.close()这里的遗漏.

使用tempfile; 将TemporaryFile自动清理的接近:

from tempfile import TemporaryFile


with TemporaryFile(prefix=fn) as tmpfile:
    tmpfile.write(XWF.Read(hItem, offset, size))
    tmpfile.seek(0)
    try:
        image = Image.open(tmpfile)
        exif_data = get_exif_data(image)
    except IOError:
        print 'Not an image'
        return

    gps = get_lat_lon(exif_data)
    if gps[0]:
        gps_data[fn] = (repr(gps[0]), repr(gps[1]))
        print('Found GPS data in %s' % fn)
    else:
        print('No GPS data in image %s' % fn)

    del image

 # tmpfile is automatically closed because we used it as a context manager
Run Code Online (Sandbox Code Playgroud)

您还希望最小化您在try块中放置的内容,仅捕获IOError实际读取图像数据的时间,而不是之前.

  • 稍微更新,我意识到`tempfile`对象也是上下文管理器. (2认同)