Home > Software design >  Convert a Text File into an Array, without the '/n'
Convert a Text File into an Array, without the '/n'

Time:05-13

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

CodePudding user response:

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))

CodePudding user response:

Try this:

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

CodePudding user response:

You can try something like this

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