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

Export a 1D list in Python in one column

When i want to export a list in a txt file it displays the elements in one line instead i want each elements in one column. For instance this list:

[1, 2, 3, 4]

I want to export it in a txt file so that my file contains in one column the elements of the list:

1
2
3
4

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

>Solution :

With one list:

with open('my_file.txt', 'w') as f:
    f.write('\n'.join(str(x) for x in my_list))

WIth two lists:

with open('my_file.txt', 'w') as f:
    to_write = ""
    for i, (a, b) in enumerate(zip(list1, list2)):
        to_write += f'{a},{b}\n' if i < len(list1) - 1 else  f'{a},{b}'
    f.write(to_write)
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