python中的这个函数将一个文件下载到aws3 bucket。我对代码有一个问题,我不想嵌套三个“If”,以便代码更清晰易读:
for fileinfo in response['Contents']:
if key in fileinfo['Key']:
if '/' in fileinfo['Key']:
filekeysplit = fileinfo['Key'].rsplit('/', 1)
if filekeysplit[1] == '':
continue
if not os.path.exists(file):
os.makedirs(file)
fileout = os.path.join(file, filekeysplit[1])
self._s3.download_file(bucket, fileinfo['Key'], fileout)
else:
self._s3.download_file(bucket, fileinfo['Key'], file)
怎么做?谢谢你
始终可以反转测试并使用
continue
跳过迭代:我们可以拉出双
^{pr2}$download_file()
调用;跳过以/
结尾的键。您只需要在循环之外创建一次目录(我在这里也将file
重命名为directory
)。我在这里用str.rpartition()
代替str.rsplit()
:我建议使用标准库的一些特性。正如Martijn Pieters所说,您应该将您的
file
变量重命名为target_directory
或类似的名称,因为如果您不这样做,可能会使代码的读者感到困惑:使用的功能包括:
fileinfo['Key'].rsplit('/', 1)
时,您似乎希望在文件路径的末尾检索文件名exist_ok
参数是^{相关问题 更多 >
编程相关推荐