pythonurldownloadsavetemporary-files

Problem downloading MEGA files with python


I am trying to download a file from my MEGA account using the following code from the mega.py library of Python:

from mega import Mega

mega = Mega()
m = mega.login('example@example.com', 'example')
file = m.find('example.txt')
m.download(file, 'D:\\Desktop')

However, it is always returning:

 Traceback (most recent call last):

  File "D:\Programas\aNaconda\lib\shutil.py", line 788, in move
    os.rename(src, real_dst)

PermissionError: [WinError 32] The file is already being used by another process: 'C:\\Users\\vrida\\AppData\\Local\\Temp\\megapy_xdste432' -> 'example.txt'


During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "<ipython-input-26-c3f75106fafb>", line 1, in <module>
    m.download(file)

  File "D:\Programas\aNaconda\lib\site-packages\mega\mega.py", line 564, in download
    return self._download_file(file_handle=None,

  File "D:\Programas\aNaconda\lib\site-packages\mega\mega.py", line 745, in _download_file
    shutil.move(temp_output_file.name, output_path)

  File "D:\Programas\aNaconda\lib\shutil.py", line 803, in move
    os.unlink(src)

PermissionError: [WinError 32] The file is already being used by another process: 'C:\\Users\\vrida\\AppData\\Local\\Temp\\megapy_example' 

Actually when I enter in the folder (C:\Users\vrida\AppData\Local\Temp) I find a temporary file like the one I'm wanting to download but named megapy_example.

I saw that the following site has a discussion to solve the problem:

https://www.reddit.com/r/learnpython/comments/mw6is2/download_file_from_mega_using_megapy/

asking to add the following lines to the code:

try:
      m.download(file, 'D:\\Desktop')
except PermissionError:
      continue

In my case, the continue command wasn't working so I simply put in the pass command. The code runs, but I don't know if the file is really saved or not.

Could someone please help me? I really need to download the files and save them.

If it doesn't work through the mega.py library, you guys would somehow know how to download from the public link like this by Python: https://mega.co.nz/#!cSZCELDb!5O57KMVMIgrPiH5fnaefWeNPDqoDWzGbY-sZkdTUdNk


Solution

  • There's a bug in the library, it's not closing the file before moving it. You could fix the bug by editing the source code:

    1. Open the file at D:\Programas\aNaconda\lib\site-packages\mega\mega.py
    2. Goto line 745 where the line shutil.move(temp_output_file.name, output_path) is.
    3. Add temp_output_file.close() right above it.
    4. Save & try again.