Created
March 25, 2019 08:15
-
-
Save kashaziz/96f29a657688d8f35b8f837d82fc7b5a to your computer and use it in GitHub Desktop.
Rename files in Dropbox using Python SDK and Dropbox API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# input name of image folder | |
image_folder = str(input("Enter folder name to fetch images: ")).lower() | |
# instantiate Dropbox connection | |
dbx = dropbox.Dropbox('dropbox access token') | |
# proceed if image folder exists in Dropbox | |
if dbx.files_get_metadata(image_folder).path_lower == image_folder: | |
# iterate through the files inside Dropbox folder | |
for file in dbx.files_list_folder(image_folder).entries: | |
# if zip files found, download, unzip and upload | |
if file.name.endswith(".zip"): | |
# download zip file and save locally | |
with open("downloaded_zip.zip", "wb") as f: | |
metadata, res = dbx.files_download(file.path_lower) | |
f.write(res.content) | |
# extract zip file using Python zipfile module | |
# folder name "image_folder" is same as on Dropbox | |
with zipfile.ZipFile("downloaded_zip.zip", "r") as zip_ref: | |
zip_ref.extractall(image_folder) | |
# upload extracted images to Dropbox | |
for root, dirs, files in os.walk(images_folder, topdown=False): | |
for name in files: | |
file_to_upload = os.path.join(root, name) | |
# create upload path and replace \ with / :: a work around from windows to linux | |
file_upload_path = dropbox_folder + file_to_upload.replace(os.path.sep, '/')[3:] | |
with open(file_to_upload, "rb") as f: | |
dbx.files_upload(f.read(), file_upload_path, mute=True) | |
# rename images files in Dropbox folder and sub-folders | |
for entry in dbx.files_list_folder(image_folder, recursive=True, include_deleted=False).entries: | |
# files_move_v2 will move file from source to destination path | |
# if both paths are same, the file will be essentially renamed. | |
dbx.files_move_v2(entry.path_display, new_file_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment