Export a 1D list in Python in one column
Question:
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
Answers:
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)
fname = "myfile.txt"
num_list = [1, 2, 3, 4]
# open the file
with open(fname,"w") as fw:
# Iterate through the elements, minus the last one
for num in num_list[:-1]:
# Write the number as a string, the concatenate a new line
fw.write(str(num)+"n")
fw.write(str(num_list[-1]))
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
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)
fname = "myfile.txt"
num_list = [1, 2, 3, 4]
# open the file
with open(fname,"w") as fw:
# Iterate through the elements, minus the last one
for num in num_list[:-1]:
# Write the number as a string, the concatenate a new line
fw.write(str(num)+"n")
fw.write(str(num_list[-1]))