0

I am trying to read a file and I am printing the content out in alphabetical order. it is only reading 6 items from the file and no more. I am not asking someone to do it for me , if someone can just guide me in the direction of what I am doing wrong here is my code so far.

  infile = open("unsorted_fruits.txt", "r")
  outfile=open("sorted_fruits.txt","w")
  fruit=infile.read(50).split()


  #outfile.write(fruit)

  fruit.sort()

  for numbers in range(len(fruit)):
      print(fruit[numbers])




  infile.close()
  outfile.close()
  • 2
    You're only reading 50 bytes... – Tatsuyuki Ishi Mar 10 '17 at 03:00
  • thank you so much that was it. – geekstudent Mar 10 '17 at 03:11
  • While we're at it, `for i in range(len(fruit)):` is an anti-pattern from recidivist C programmers. Just iterate directly instead of generating indices and indexing: `for afruit in fruit: print(afruit)`. It's faster (indexing is surprisingly costly compared to direct iteration) and self-documenting (no anonymous `i` names, you're naming the item being populated on each loop). – ShadowRanger Mar 10 '17 at 03:11
  • Ahh ok I see, it makes sense and it works. So it is better to do it that way every time? I am not sure I undertand why afruit prints the items – geekstudent Mar 10 '17 at 03:29

1 Answers1

0

Try .read() to set fruit to the entire file split.

Also, try using context managers so you don't have to call close() by yourself:

with open("unsorted_fruits.txt", "r") as infile:
    #... do your stuff
    #close will be called automatically 

If you're concerned about massive files, then consider other questions that read large files in batches: Lazy Method for Reading Big File in Python?

In the code sample you provided outfile is not used (commented out) but you can use nested context managers.

Community
  • 1
  • 1
Tommy
  • 12,588
  • 14
  • 59
  • 110