AnalyseMorphologique/utils/files/output.py
2023-04-25 13:31:51 +02:00

48 lines
1.4 KiB
Python

"""
This module is used to manage the output files of the program.
"""
def format_data(data:dict, separator:str, selected_columns:list = None) -> str:
"""
Format the data to be saved in the output file.
:param data: Data to be formatted
:param selected_columns: Columns to be saved
:param separator: Separator of the columns
:return: Formatted data
Example:
>>> data = {
... 'col1': [1, 2, 3],
... 'col2': [4, 5, 6],
... 'col3': [7, 8, 9]
... }
>>> format_data(data, separator=';')
'col1;col2;col3
1 ;4 ;7
2 ;5 ;8
3 ;6 ;9
'
"""
output = ''
if selected_columns is None:
selected_columns = list(data.keys())
for column_name in selected_columns:
output += column_name.ljust(len(column_name) if len(column_name) > 8 else 9 ) + separator
output += '\n'
for i in range(len(data[selected_columns[0]])):
for column in selected_columns:
output += str(data[column][i]).ljust(len(column) if len(column) > 8 else 9 ) + separator
output += '\n'
return output
def save_output_file(output_file:str, content:str):
"""
Save the output file.
:param output_file: Path to the output file
:param content: Content of the output file
"""
with open(output_file, 'w') as f:
f.write(content)