简体   繁体   English

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

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

I am getting the error while deleting the files in folder.删除文件夹中的文件时出现错误。
Below is my code.下面是我的代码。

Part-1 of coding 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 of coding 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))

Error I am getting is as below:我得到的错误如下:

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

You forgot to write你忘了写

cover.close()

After the line:行后:

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

Because of that, you still have an opened file and you cannot delete it.因此,您仍然有一个打开的文件,您无法删除它。

Try replacing this:尝试替换这个:

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

With:和:

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

Using with should help with situations where you may forget to close the file once you're done using it.使用with应该有助于解决使用完文件后可能忘记关闭文件的情况。

My problem is solved now:)我的问题现在解决了:)

Actually I used其实我用过

cover.close()

insted of安装的

cover.close

And I used this code before line我在行前使用了这段代码

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