I have the following piece of code in which I have been thinking on how to write it more concisely. In the lines bellow I have a variable called export_path
which may be given by the user or not, and in case it is given, the generated file will be exported to that folder. However, in case it is None
, then the files are exported to the 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)
My problem is, I would like to avoid this if/else block and make it cleaner. My main struggle so far is regarding on how to deal with the variable export_path
when it is none. Ideally, I would like to do something like this:
export_directory = export_path + f'/{project_name}'
with open(export_directory, 'w') as file:
file.write(text)
And in case export_path
is None
, then would only export to the CWD. But, the problem here is that obviously you cannot sum a Nonetype and a string. So here it comes my question, it somehow to handle this Nonetype
in such a way that it would make it possible to create a one-liner path?
Are you looking for something like this?
exp_directory = export_path if export_path is not None else f"{project_name}"