sleepylog sleepylog - 5 months ago 17
Python Question

Why is there a gap between the lines of text?

I can't figure out why there is a space between each line of text when I run this code:

file = open("Children.txt", 'a')
file.write("\n" + childName)

file = open("Children.txt", 'r')
lineList = file.readlines()
print("List of children's names in alphabetical order:")
for line in lineList:

The spaces between each line only appear when I use the sorted() function. If I don't include it in the code and just use the print(file) function, the results display without a space between the lines of text. However I need the results to display alphabetically and that's why I use the sorted() function.

Answer Source

f.readlines() does not strip trailing newlines when reading in the file. Your list items will contain a trailing newline, which is printed out. Incidentally, print also adds a newlines at the end of input, meaning each line is printed with two newlines.

You can change this by either stripping newlines, or printing with end="":

for line in lineList: 
    print(line.rstrip())  # or print(line, end="")

Furthermore, sorted is not an inplace function. If you want to sort inplace, call .sort().