'Convert a Text File into an Array, without the '/n'

I am trying to code a sorting code, very basic, using the python "(sorted)" method. For this code, I am trying to import the words to be sorted by using a text file. I would like to import the data from the text file (.txt) to be clear. This is not the problem, its the output. Here is the code, and the output.

text_file = open("WordsToSort-For-AlphabeticalSortProgram.txt", "r")
ListToSort = text_file.readlines()
text_file.close()

print(sorted(ListToSort, key=str.lower))

For more clarity, here is the data in the .txt file

Banana
Apple
Canada

Here is the output:

['Apple\n', 'Banana\n', 'Canada\n']

How do I make it so that it does not output the "\n" at the end of each word in the output?

EDIT: Formatting



Solution 1:[1]

Try this:

with open(txt, 'r') as fp:
  lines = fp.readlines() 
for i in range(0, len(lines)):
    ListToSort.append(lines[i].rstrip('\n'))

Solution 2:[2]

You can try something like this

lines = [line.strip('\n') for line in open('your file name', 'r').readlines()]

Solution 3:[3]

As posted by @Barmar in the comments, the following code is working, with the output I am looking for.

text_file = open("WordsToSort-For-AlphabeticalSortProgram.txt", "r")
ListToSort = text_file.read().splitlines()
text_file.close()

# save for testing: ListToSort = ["a", "C", "b"]

print(sorted(ListToSort, key=str.lower))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 anbocode
Solution 3 CozmoKitten