How to write a statement and an array to individual lines on a text file? Python

Question:

a = str(mergeSort(lines))
nlines = ['Sorted Numbers',a]
with open('SortedNumbers.txt', 'w') as f:
    f.writelines(nlines)enter code here

mergeSort(lines) is my array of a few numbers. With this code above, the text file it creates does everything I want except all of it is on one line. How do I get it so the text file it produces will be

Sorted Numbers
1
3
5
8
10
Asked By: thiccdan69

||

Answers:

a = "n".join(mergeSort(lines));

Should put a newline after each of the numbers of your array.

It should print properly afterwards

Answered By: 0xRyN

This should work.

a = mergeSort(lines)
nlines = "Sorted Numbersn" + "n".join([str(i) for i in a])
with open('SortedNumbers.txt', 'w') as f:
    f.write(nlines)

or


a = mergeSort(lines)
nlines = ["Sorted Numbers"] + [str(i) for i in a]  # if lines are integers
# nlines = ["Sorted Numbers"] + a               # if lines are strings
with open('SortedNumbers.txt', 'w') as f:
    f.writelines(nlines)
Answered By: Alexander

Don’t convert the array to a string. And also write the text separately rather than trying to build an array with the title.

a = mergeSort(lines)
with open('SortedNumbers.txt', 'w') as f:
    f.write("Sorted Numbers")
    f.writelines(a)
Answered By: Code-Apprentice
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.