Python 如何将此代码重构为嵌套不超过3“;如果;
python中的此函数将文件下载到AWS S3 bucket。我对代码有一个问题,我不想嵌套三个“如果”,以便代码更清晰可读:Python 如何将此代码重构为嵌套不超过3“;如果;,python,Python,python中的此函数将文件下载到AWS S3 bucket。我对代码有一个问题,我不想嵌套三个“如果”,以便代码更清晰可读: for fileinfo in response['Contents']: if key in fileinfo['Key']: if '/' in fileinfo['Key']: filekeysplit = fileinf
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)
怎么做?谢谢您可以随时反转测试并使用
继续
跳过迭代:
for fileinfo in response['Contents']:
if key not in fileinfo['Key']:
continue
if '/' not in fileinfo['Key']:
self._s3.download_file(bucket, fileinfo['Key'], file)
continue
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)
我们可以拉出doubledownload\u file()
调用;跳过以/
开头的键。您只需要在循环之外创建一次目录(这里我也将文件
重命名为目录
)。我会在这里使用str.rpartition()
而不是str.rsplit()
:
我想建议使用标准库的一些功能。正如Martijn Pieters所说,您应该将
文件
变量重命名为目标目录
或类似的内容,因为如果您不:
for fileinfo in response['Contents']:
filepath_retrieved = fileinfo['Key']
if key in filepath_retrieved:
pathname_retrieved, filename_retrieved = os.path.split(filepath_retrieved)
if pathname_retrieved:
if filename_retrieved:
os.makedirs(target_directory, exist_ok=True)
output_filepath = os.path.join(target_directory, filename_retrieved)
self._s3.download_file(bucket, filepath_retrieved, output_filepath)
else:
output_filepath = target_directory
self._s3.download_file(bucket, filepath_retrieved, output_filepath)
使用的功能包括:
- 而不是str.rsplit()或str.rpartition(),因为当您尝试执行
fileinfo['Key'].rsplit('/',1)
的参数,这样在创建目录之前就不必担心目录的存在exist\u ok
self.\u s3.下载文件
也应修复。。。2) 日志应该建立在工作功能之上。。。不要混用。因此,以/
结尾的键是无效的,也应该跳过它?有一个问题,如果filekeysplit[1]='':@Cloudgls:谢谢,我刚才重写了一些,但忘了将其放回,那么您忘记在条件之前计算`filekeysplit`的值。另一个更新即将到来。
for fileinfo in response['Contents']:
filepath_retrieved = fileinfo['Key']
if key in filepath_retrieved:
pathname_retrieved, filename_retrieved = os.path.split(filepath_retrieved)
if pathname_retrieved:
if filename_retrieved:
os.makedirs(target_directory, exist_ok=True)
output_filepath = os.path.join(target_directory, filename_retrieved)
self._s3.download_file(bucket, filepath_retrieved, output_filepath)
else:
output_filepath = target_directory
self._s3.download_file(bucket, filepath_retrieved, output_filepath)