如何重构此代码以使嵌套不超过3个“if”

2024-10-03 11:13:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

怎么做?谢谢你


Tags: pathkey函数代码inselfifs3
2条回答

始终可以反转测试并使用continue跳过迭代:

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)

我们可以拉出双download_file()调用;跳过以/结尾的键。您只需要在循环之外创建一次目录(我在这里也将file重命名为directory)。我在这里用str.rpartition()代替str.rsplit()

^{pr2}$

我建议使用标准库的一些特性。正如Martijn Pieters所说,您应该将您的file变量重命名为target_directory或类似的名称,因为如果您不这样做,可能会使代码的读者感到困惑:

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.r分区()因为当您尝试执行fileinfo['Key'].rsplit('/', 1)时,您似乎希望在文件路径的末尾检索文件名
  • exist_ok参数是^{}的,所以在创建目录之前不必担心目录的存在。在

相关问题 更多 >