繁体   English   中英

Python - 无法使用 python 从文件夹中删除文件

[英]Python - Unable to delete files from folder using python

删除文件夹中的文件时出现错误。
下面是我的代码。

Part-1 编码

pdf = FPDF()
sdir = "D:/IMAGES/"
w, h = 0, 0

for i in range(1, 25):
    fname = (sdir + str(i) + ".jpeg")
    if os.path.exists(fname):
        if i == 1:
            cover = Image.open(fname)
            w, h = cover.size
            pdf = FPDF(unit="pt", format=[w, h])
        image = fname
        pdf.add_page()
        pdf.image(image, 0, 0, w, h)
    else:
        pdf.output(
            r"D:\DOCUMENTS\Google Drive\NewsPapers\Lokmat\Lokmat Mumbai Main "+str(d+A+Y)+".pdf", "F")
        pdf.close

Part-2 编码

import os
dir_name = "D:/IMAGES/"
test = os.listdir(dir_name)

for item in test:
    if item.endswith(".jpeg"):
        os.remove(os.path.join(dir_name, item))

        print("Done")
print("--- %s seconds ---" % (time.time() - start_time))

我得到的错误如下:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'D:/IMAGES/1.jpeg'

你忘了写

cover.close()

行后:

pdf = FPDF(unit="pt", format=[w, h])

因此,您仍然有一个打开的文件,您无法删除它。

尝试替换这个:

cover = Image.open(fname)
w, h = cover.size
pdf = FPDF(unit="pt", format=[w, h])

和:

with Image.open(fname) as cover:
    w, h = cover.size
    pdf = FPDF(unit="pt", format=[w, h])

使用with应该有助于解决使用完文件后可能忘记关闭文件的情况。

我的问题现在解决了:)

其实我用过

cover.close()

安装的

cover.close

我在行前使用了这段代码

pdf.output(r"D:\DOCUMENTS\Google Drive\NewsPapers\Lokmat\Lokmat Mumbai Main "+str(d+A+Y)+".pdf", "F")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM