0

I created three text files that each have 10 random numbers separated by commas. I then have a python program that accepts the name of a text file from the user, reads the numbers from the text file into a list, and then sorts and prints the original list and the sorted list.

prompt = raw_input("Enter the name of the text file you want to open: ")
fileopen = open(prompt)
for line in fileopen:
numbers = line.split(",")
sortednumbers = sorted(numbers)
print numbers
print sortednumbers

However, the resulting lists that are printed always contain exactly one value that has a "\n" attached to the end of the number (e.g. 99\n). I've noticed it's always the last number in the text file. How can I get it to just display the numbers from the text files without the "\n"?

MrFlom
  • 99
  • 10
  • What language are you programming in? – scunliffe Sep 25 '14 at 18:25
  • 1
    I dont understand algorithm list and sorting tags! – Lrrr Sep 25 '14 at 18:44
  • 1
    possible duplicate of [How can I remove (chomp) a newline in Python?](http://stackoverflow.com/questions/275018/how-can-i-remove-chomp-a-newline-in-python) – darthbith Sep 25 '14 at 19:08
  • 1) Always use [`with`](https://docs.python.org/2/reference/compound_stmts.html#the-with-statement) to open files, so that closing the file is handeled automatically. 2) Use `strip` or `rstrip`, as in `numbers = line.strip().split(',')`. See:http://stackoverflow.com/questions/275018/how-can-i-remove-chomp-a-newline-in-python – darthbith Sep 25 '14 at 19:09

1 Answers1

0

Thanks darthbith! This worked:

Use strip or rstrip, as in numbers = line.strip().split(',')

MrFlom
  • 99
  • 10