Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error 32, Python, file being used by another process

Tags:

python

I have a simple program, which looks for all compressed folders in a directory, targets one compressed file, gets an excel file located inside the compressed file and moves it to another location (it does this for every excel file, for how many ever compressed folders):

path = 'C:\Users\me\Documents\Extract'
new_path = 'C:\Users\me\Documents\Test'
i = 0
for folder in os.listdir(path):
        path_to_folder = os.path.join(path, folder)

        zfile = zipfile.ZipFile(os.path.join(path, folder))
        for name in zfile.namelist():
            if name.endswith('.xls'):
                new_name = str(i)+'_'+name
                new_path = os.path.join(new_path, new_name)
                zfile.close()
                #os.rename(path_to_folde, new_path) -- ERROR HERE
                shutil.move(path_to_folde, new_path) -- AND ERROR HERE
        i += 1

I have tried 2 ways to move the excel file os.rename and shutil.move. I keep on getting an error:

WindowsError: [Error 32] The process cannot access the file beacause it is being used by another process.

I don't understand why this error persists, since I have closed every folder.

like image 352
Max Kim Avatar asked Jun 13 '13 19:06

Max Kim


2 Answers

path = 'C:\Users\me\Documents\Extract'
destination_path = 'C:\Users\me\Documents\Test'
i = 0
for folder in os.listdir(path):
    path_to_zip_file = os.path.join(path, folder)

    zfile = zipfile.ZipFile(path_to_zip_file)
    for name in zfile.namelist():
        if name.endswith('.xls'):
            new_name = str(i)+'_'+name
            new_path = os.path.join(destination_path, new_name)
            # This is obviously going to fail because we just opened it
            shutil.move(path_to_zip_file, new_path)
    i += 1
    zfile.close()

Changed some of the variable names in your code snippet. Do you see your problem now? You're trying to move the zip file that your process has open. You'll need to copy the .xls file to your destination using the zipfile module.

like image 120
OregonTrail Avatar answered Nov 12 '22 12:11

OregonTrail


If you are on a windows computer go to the task manager and hit the processes tab. Scroll down to anything that says python and end the process. You may have had python running with something else. Then try running your python program again and it should work.

like image 32
Mike El Jackson Avatar answered Nov 12 '22 12:11

Mike El Jackson