Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Write python results in an excel file, different columns

I know similar questions have been asked before, however, I cannot edit my code to fit:

I have a python script that writes all combinations of 15 numbers in a txt file:

import itertools
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
combinations = list(itertools.combinations(numbers, 15))
#print(combinations)

#Write combinations to a file
with open('combinations.txt', 'w') as f:
    for comb in combinations:
        f.write(str (comb) + '\n')

For some unknown reason, results come in parenthesis:
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I need to write onto a xlsb file, each number in a column without parenthesis or commas, the expected result is below:

excel

…with centralized text and fixed column width
Any ideas of a simple and small code? I already have pandas and openpyxl (if it helps)

>Solution :

You can’t create a xlsb file directly, you can however first create an xlsx file and then convert.

Note that you don’t need for that, better use openpyxl directly. Also, don’t create all combinations with list, that will unnecessarily take a lot of space in memory if there are many combinations, rather loop directly over the output of combinations:

from openpyxl import Workbook
import itertools

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

wb = Workbook()
ws = wb.active

for comb in itertools.combinations(numbers, 15):
    ws.append(comb)
    
wb.save('combinations.xlsx')

To then convert to xlsb, follow this approach (which requires windows and Excel).

Output:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading