Upload files through Python Wrapper around Mega api - python-2.7

I'm using python 2.7 Wrapper of Mega Api on Ubuntu. With the following code I could upload a set of files to my Mega Account, however I'd like to know how I can upload files to a specific folder on my account.
from mega import Mega
import os
from os import listdir
from os.path import isfile, join
mega = Mega()
mega._login_user('email','password')
def absoluteFilePaths(directory):
for dirpath,_,filenames in os.walk(directory):
for f in filenames:
yield os.path.abspath(os.path.join(dirpath, f))
directory = '/home/caioignm/test_folder'
file_path_generator = absoluteFilePaths(directory)
for file_path in file_path_generator:
mega.upload(file_path)
On my Mega Account, I have one folder, 'Personal', with other folder inside, 'Vacations', where all my files are stored. When I upload without refering a destination path, the files are stored in root directory.
I tried to follow help instructions of mega package, but I didn't find out how to set destination folder of my files.
Help on method upload in module mega.mega:
upload(self, filename, dest=None, dest_filename=None) method of mega.mega.Mega instance
##########################################################################
# UPLOAD
Doing mega.upload('filename', 'Personal/Vacations') I haven't received any error message, but my files were not uploaded too

It was so easy, like this:
Folder = mega.find('my_mega_folder')
mega.upload('yourfile.txt', Folder[0])
I have added it to your code:
from mega import Mega
import os
from os import listdir
from os.path import isfile, join
mega = Mega()
mega._login_user('email','password')
def absoluteFilePaths(directory):
for dirpath,_,filenames in os.walk(directory):
for f in filenames:
yield os.path.abspath(os.path.join(dirpath, f))
directory = '/home/caioignm/test_folder'
file_path_generator = absoluteFilePaths(directory)
Folder = mega.find('your_folder') #change it with the folder in your mega
for file_path in file_path_generator:
mega.upload(file_path, Folder[0])

Upload a file to a destination folder:
folder = m.find('my_mega_folder')
m.upload('myfile.doc', folder[0])
Source : https://pypi.org/project/mega.py/

Related

Python request download a file and save to a specific directory

Hello sorry if this question has been asked before.
But I have tried a lot of methods that provided.
Basically, I want to download the file from a website, which is I will show my coding below. The code works perfectly, but the problem is the file was auto download in our download folder path directory.
My concern is to download the file and save it to a specific folder.
I'm aware we can change our browser setting since this was a server that will remote by different users. So, it will automatically download to their temporarily /users/adam_01/download/ folder.
I want it to save in server disk which is, C://ExcelFile/
Below are my script and some of the data have been changing because it is confidential.
import pandas as pd
import html5lib
import time from bs4
import BeautifulSoup
import requests
import csv
from datetime
import datetime
import urllib.request
import os
with requests.Session() as c:
proxies = {"http": "http://:911"}
url = 'https://......./login.jsp'
USERNAME = 'mwirzonw'
PASSWORD = 'Fiqr123'
c.get(url,verify= False)
csrftoken = ''
login_data = dict(proxies,atl_token = csrftoken, os_username=USERNAME, os_password=PASSWORD, next='/')
c.post(url, data=login_data, headers={"referer" : "https://.....com"})
page = c.get('https://........s...../SearchRequest-96010.csv')
location = 'C:/Users/..../Downloads/'
with open('asdsad906010.csv', 'wb') as output:
output.write(page.content )
print("Done!")
Thank you, be pleased to ask if any confusing information was given.
Regards,
Fiqri
It seems that from your script you are writing the file to asdsad906010.csv. You should be able to change the output directory as follows.
# Set the output directory to your desired location
output_directory = 'C:/ExcelFile/'
# Create a file path by joining the directory name with the desired file name
file_path = os.path.join(output_directory, 'asdsad906010.csv')
# Write the file
with open(file_path, 'wb') as output:
output.write(page.content)

Ziping a File in python and moving it

In the script when I have zip it up a file in say C:/Users/User/Desktop/Folder, it shows up as a zip file in the structure of ZipFile.zip/C:/Users/user/Desktop/Folder instead of just ZipFile.zip/Folder and I can't figure out how to fix it. [Zipping code is lines 21-26]
I'm also trying to move the created zip file to the specified back up device [line 27]
My code is :
import os
import sys
import shutil
import zipfile
import traceback
print ('Welcome to USB Backup Utility')
print ('Created by: TheCryptek')
print ('\nWhat directory would you like to back up?')
print ('Example: C:/users/user/Desktop/Folder')
backUp = raw_input('> ') # Files the user specified to back up
print ('\nWhere would you like to back these files up at?')
print ('Example USB Letter: E:/')
backDevice = raw_input('> ') # Device the user specified to save the back up on.
print ('\nName of the zip file you prefer?')
print ('Example: Backup.zip')
backZip = raw_input('> ') # The name of the zip file specified by the user
print ('\nBackup started...')
if not os.path.exists(backDevice + '/BackUp'): # If the BackUp folder doesn't exist on the device then
os.mkdir(backDevice + 'BackUp') # Make the backup folder on usb device
backZip = zipfile.ZipFile(backZip, 'w') # Not sure what to say for lines 21 - 26
for dirname, subdirs, files in os.walk(backUp):
backZip.write(dirname)
for filename in files:
backZip.write(os.path.join(dirname, filename))
backZip.close()
shutil.move(backZip, backDevice + '/BackUp') # Move the zip files created in working directory to the specified back up device -[ Something is wrong with this can't figure out what ]-
print('Backup finished.')
For shutil.move() you have to give proper source and destination paths.
And in your program,the source path and file object are of same names.so it is calling that object instead it should take the path of file.
import os
import sys
import shutil
import zipfile
import traceback
print ('Welcome to USB Backup Utility')
print ('Created by: TheCryptek')
print ('\nWhat directory would you like to back up?')
print ('Example: C:/users/user/Desktop/Folder')
backUp = raw_input('> ') # Files the user specified to back up
print ('\nWhere would you like to back these files up at?')
print ('Example USB Letter: E:/')
backDevice = raw_input('> ') # Device the user specified to save the back up on.
print ('\nName of the zip file you prefer?')
print ('Example: Backup.zip')
backZip = raw_input('> ') # The name of the zip file specified by the user
print ('\nBackup started...')
if not os.path.exists(backDevice + '/BackUp'): # If the BackUp folder doesn't exist on the device then
os.mkdir(backDevice + 'BackUp') # Make the backup folder on usb device
bkZip = zipfile.ZipFile(backZip, 'w') # Not sure what to say for lines 21 - 26
for dirname, subdirs, files in os.walk(backUp):
bkZip.write(dirname)
for filename in files:
bkZip.write(os.path.join(dirname, filename))
bkZip.close()
#print backZip,backDevice
dest = backDevice + '/BackUp'
#print dest
shutil.move(backZip, dest) # Move the zip files created in working directory to the specified back up device -[ Something is wrong with this can't figure out what ]-
print('Backup finished.')
You have to make an absolute path for it probs.

I have a flask application that I would like to convert into an executable

I have a flask application that I would like to convert into an executable for deploying elsewhere. I have used py2exe for that. I am getting jinja2:TemplateNotFound error. I have copied the static and templates folders into the dist folder where the exe files reside. Pls let me know if I am missing something. My setup file is as follows:
from distutils.core import setup
import py2exe
import os
from glob import glob
import sys
from distutils.filelist import findall
import matplotlib
matplotlibdatadir = matplotlib.get_data_path()
matplotli bdata = findall(matplotlibdatadir)
matplotlibdata_files = []
for f in matplotlibdata:
dirname = os.path.join('matplotlibdata', f[len(matplotlibdatadir)+1:])
matplotlibdata_files.append((os.path.split(dirname)[0], [f]))
data_files=[('static', glob("D:\\pythonLearning\\static\\*.*")), ('templates', glob("D:\\pythonLearning\\templates\\login.html"))]
data_files.extend(matplotlibdata_files)
print data_files
sys.path.append('C:\\Windows\\winsxs\\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.6161_none_50934f2ebcb7eb57')
setup( console=['myfile.py'],
options={ 'py2exe': { 'packages' : ['matplotlib', 'pytz','werkzeug','email','jinja2.ext'],
'includes': ['flask','jinja2'] } },
data_files=data_files )
This is because jinja expects your egg to be unzipped and available via the filepath. See for more information.
You can workaround this for typical data files using this
but jinja2 has no direct support for this and you would have to implement this yourself

Upload an mp3 files to soundcloud using Python (file name is random)

I'd like to upload an mp3 file from hotfolder without knowing the name of the file. (such as *.mp3)
here's what I tried (to upload specific file / known file name)
import soundcloud
# create client object with app and user credentials
client = soundcloud.Client(client_id='***',
client_secret='***',
username='***',
password='***')
# print authenticated user's username
print client.get('/me').username
mp3_file=('test.mp3')
# upload audio file
track = client.post('/tracks', track={
'title': 'Test Sound',
'asset_data': open(mp3_file, 'rb')
})
# print track link
print track.permalink_url
how can I make the script upload any mp3 file in that folder ? (script and files are located in the same folder)
From the language as written here, it's not precisely clear what you mean by "upload any mp3 file in that folder." Does uploading the first file in the folder satisfy your need, or does it need to be a different file each time the script executes? If the latter, my suggestion is to get a list of files and then randomly select one of them.
To get a list of all files in python,
from os import listdir
from os.path import isfile, join
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
and then to randomly select one of them:
import random
print(random.choice(onlyfiles))
Hope this helps

Zipping a file from a directory and placing it in another Directory

I am trying to set up a program to put my minecraft server world into a zip and place it into another directory on another drive (/media/500gb/MinecraftWorldBackups)
But I keep getting this error
Although the folder doesn't contain a folder or file called 'h'
What do I need to do to fix this I believe it is due to file and folder?
#!/usr/bin/env python
import time, zipfile
while True:
FileName = 'MinecraftBackup_' + str(int(time.time()))
Path = '/home/bertie/Desktop/FeedTheBeastServer/world/'
print(FileName)
Zip = zipfile.ZipFile('/media/500gb/MinecraftWorldBackups/'+FileName+'.zip','w')
for each in Path:
print(each)
try: Zip.write(Path + each)
except IOError: None
Zip.Close()
print('Done')
time.sleep(60)