Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hello , I am having trouble with some code I am writing. I have a data structure

ID: 3601375 • Letter: H

Question

Hello , I am having trouble with some code I am writing. I have a data structures assignment and my code is giving me errors. Every time I fix 1 error I have another. I believe it is because I am using python 3.4. This is the code I have so far...

file = open('C:Python34unsorted_fruits.txt','r')
outfile=open('C:Python34sorted_fruits.txt','w')

#readlines return a list
fruits=file.readlines()

#list.sort() do an inline sort
fruits.sort()

#remove the blank lines and write the file
for fruit in fruits:
if fruit != ' ': #if fruit is blank, skip the write
outfile.write(fruits) #otherwise write the fruit to the output file
  
#close the input and output file
file.close()
outfile.close()

My goal is to take a file with unsorted fruits and to creat a new file with sorted fruits. Any help would be awesome! I need code to be combatable with 3.4 python.

Explanation / Answer

The code seems fine.

Two modifications suggested:

if fruit != ' ':
   outfile.write(fruit)
   outfile.write(" ")

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote