繁体   English   中英

如何解决这个 python 错误 - PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:

[英]How to tackle this python error - PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:

我正在尝试借助“shutil”模块将文件“A”的内容传输到“temp”文件中。 但是,我得到以下错误:

[WinError 32] The process cannot access the file because it is being used by another process

我也尝试在谷歌中研究同样的错误,但没有一个对我有帮助。 我不确定出了什么问题。

我正在使用 windows 10(64 位),我的 python 版本是 3.7。

编码细节如下:

    import csv
    import shutil
    from tempfile import NamedTemporaryFile
    import os

    class csvtest():

        def editcsv1(self,filename):  
            filename="data.csv"
            tempfile=NamedTemporaryFile(delete=False,dir=r"C:\Users\Sahil\Desktop\python")
            with open(filename,"r") as csvfile2,open(tempfile.name,"w") as temp_file:
            reader=csv.reader(csvfile2)
            writer=csv.writer(temp_file)

            for row in reader:
                writer.writerow(row)
                csvfile2.close()
                temp_file.close()
                os.unlink(temp_file.name)
            shutil.move(temp_file.name,filename)

    abc=csvtest()
    abc.editcsv1(filename)

'''

根据要求,回溯消息如下:'''

runfile('C:/Users/Sahil/Desktop/python/stackoverflow5may.py',wdir='C:/Users/Sahil/Desktop/python')

文件“”,第 1 行,在 runfile('C:/Users/Sahil/Desktop/python/stackoverflow5may.py', wdir='C:/Users/Sahil/Desktop/python')

文件“C:\Users\Sahil\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py”,第 827 行,运行文件 execfile(文件名,命名空间)

文件“C:\Users\Sahil\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py”,第 110 行,在 execfile exec(compile(f.read(), filename, 'exec'), namespace)

文件“C:/Users/Sahil/Desktop/python/stackoverflow5may.py”,第 23 行,在 abc.editcsv1(文件名)中

文件“C:/Users/Sahil/Desktop/python/stackoverflow5may.py”,第 20 行,在 editcsv1 shutil.move(temp_file.name,filename)

文件“C:\Users\Sahil\Anaconda3\lib\shutil.py”,第 578 行,在 move os.unlink(src)

PermissionError: [WinError 32] 该进程无法访问该文件,因为它正被另一个进程使用:'C:\Users\Sahil\Desktop\python\tmp2gibk4eh'

'''

NamedTemporyFile返回一个打开的文件 object 但您尝试使用open(tempfile.name,"w") as temp_file temp_file 再次打开它。 您的 for 循环中有一个错误(关闭每行写入的文件)。 所以,

import csv
import shutil
from tempfile import NamedTemporaryFile
import os

class csvtest():

    def editcsv1(self,filename):  
        filename="data.csv"
        with NamedTemporaryFile(dir=r"C:\Users\Sahil\Desktop\python",
                mode="w", delete=False) as tempfile:
            with open(filename,"r") as csvfile2:
                reader=csv.reader(csvfile2)
                writer=csv.writer(tempfile)
                writer.writerows(reader)
        shutil.move(temp_file.name,filename)
        os.remove(f.name)


abc=csvtest()
abc.editcsv1(filename)

暂无
暂无

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

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