Dropbox文件分类代码执行中断及新增文件未识别问题求助
解决Dropbox文件分类代码的两个问题:中途停止与无法识别新增文件
问题原因分析
代码中途停止(执行到第24个文件就停)
Dropbox的files_list_folderAPI采用分页返回结果,单次请求只会返回有限数量的条目(默认上限1000条,但你的场景中第一页刚好只有24条)。原代码只处理了第一页的结果,没有继续获取后续分页的内容,导致遍历提前终止。无法识别新增文件
- 如果是上次执行代码后新增的文件:原代码只获取了第一页的文件列表,新增文件可能落在后续未处理的分页中,因此无法被识别。
- 如果是代码执行过程中新增的文件:由于代码在启动时就一次性获取了所有文件列表,执行过程中新增的内容不会被动态纳入遍历范围,需要重新运行代码才能扫描到。
修复后的完整代码
import os import dropbox # Replace 'YOUR_ACCESS_TOKEN' with your Dropbox access token ACCESS_TOKEN = '' def main(): # Initialize the Dropbox client dbx = dropbox.Dropbox(ACCESS_TOKEN) # List all files in the source folder (handle pagination) source_folder = "/ALL_NDA_SAMPLES" result = dbx.files_list_folder(source_folder, recursive=True) all_entries = [] # Fetch all pages of results while result.has_more: all_entries.extend(result.entries) result = dbx.files_list_folder_continue(result.cursor) all_entries.extend(result.entries) # List all files in the destination folder (handle pagination and filter files) destination_folder = "/ALL_NDA_SAMPLES/!ALLVINTAGE" dest_result = dbx.files_list_folder(destination_folder) existing_files = set() while dest_result.has_more: # Only add file names (exclude folders) existing_files.update(f.name for f in dest_result.entries if isinstance(f, dropbox.files.FileMetadata)) dest_result = dbx.files_list_folder_continue(dest_result.cursor) existing_files.update(f.name for f in dest_result.entries if isinstance(f, dropbox.files.FileMetadata)) # Copy files containing "Vintage" in the name to the destination folder for entry in all_entries: if isinstance(entry, dropbox.files.FileMetadata) and "Vintage" in entry.name: if entry.name not in existing_files: source_path = entry.path_display destination_path = os.path.join(destination_folder, entry.name) # Add error handling to avoid single file failure stopping the program try: dbx.files_copy(source_path, destination_path) print(f"Copied: {entry.name}") except dropbox.exceptions.ApiError as e: print(f"Failed to copy {entry.name}: {str(e)}") else: print(f"Already copied: {entry.name}") if __name__ == "__main__": main()
关键修复点说明
- 处理API分页:通过
has_more判断是否还有后续分页,使用files_list_folder_continue和cursor循环获取所有文件条目,确保不会遗漏任何文件。 - 过滤目标文件夹内容:只收集目标文件夹中的文件(排除文件夹),避免误判文件夹名称导致的逻辑错误。
- 添加异常处理:在文件复制操作外层增加try-except块,避免单个文件复制失败导致整个程序终止。
额外说明
如果需要实时监测Dropbox文件夹中的新增文件并自动处理,需要使用Dropbox的Webhooks功能(监听文件夹变化事件),这需要额外的服务器端部署和配置,适合长期运行的自动化场景。
内容的提问来源于stack exchange,提问作者totzillarbeats
相关产品推荐
相关产品推荐

