处理路径的无类型

问题描述 投票:0回答:1

我有以下代码段,我一直在思考如何更简洁地编写它。在下面的几行中,我有一个名为export_path的变量,该变量可以由用户提供或不提供,如果给出,则生成的文件将导出到该文件夹​​。但是,如果它是None,则文件将导出到CWD。

if export_path is not None:
    export_directory = export_path + f'/{project_name}'
    with open(export_directory, 'w') as file:
        file.write(text)
else:
    with open(f'{project_name}', 'w') as file:
        file.write(text)

我的问题是,我想避免这种if / else障碍,并使它更整洁。到目前为止,我的主要工作是关于在变量export_path不存在时如何处理。理想情况下,我想做这样的事情:

export_directory = export_path + f'/{project_name}'
with open(export_directory, 'w') as file:
     file.write(text)

并且如果export_pathNone,则只会导出到CWD。但是,这里的问题是,显然您不能对Nonetype和字符串求和。因此,这是我的问题,它以某种方式处理此Nonetype,从而可以创建单线路径?

python dry
1个回答
0
投票

您是否正在寻找类似的东西?

exp_directory = export_path if export_path is not None else f"{project_name}"
© www.soinside.com 2019 - 2024. All rights reserved.