Respuesta :
Here you go:
infile = open("unsorted_fruits.txt", "r")
lines = infile.read().splitlines()
i = 0
while i < len(lines)-1:
if lines[i+1] < lines[i]:
tmp = lines[i]
lines[i] = lines[i+1]
lines[i+1] = tmp
if i > 0:
i -= 1
else:
i += 1
outfile = open("sorted_fruits.txt", "w")
outfile.write('\n'.join(lines) + '\n')
Answer:
For the given problem, prompts the user to open the unsorted text file in read mode and unsorted file in write mode. Read the lines of unsorted file and store them in a list namely fruits. After this, sort the list using sort() function. Now, check the blank lines and write them in sorted text file. In the last, close both the unsorted and sorted file.
Further Explanation:
Code: Following is the python code that reads the fruits from "unsorted_fruits.txt" and writes in alphabetical order in the file "sorted_fruits.txt".
#open the unsorted file in read mode
inputfile = open("unsorted_fruits.txt", "r")
#open the sorted file in write mode
outputfile=open("sorted_fruits.txt","w")
#reading the lines of input file and store them in a list
fruits = inputfile.readlines()
#sort the list that contains fruits
fruits.sort()
#first remove the blank lines and write into the output file
For fruit in fruits:
If fruit != ”\n”
outputfile.write(fruit)
#close the input file
inputfile.close()
#close the output file
outputfile.close()
Learn more:
1. A company that allows you to license software monthly to use online is an example of ? brainly.com/question/10410011
2. Prediction accuracy of a neural network depends on _______________ and ______________. brainly.com/question/10599832
3. The shape of our galaxy was determined ‘on the inside looking out' by surveying the milky way using ____________ telescopes. brainly.com/question/7866623
Answer details:
Grade: College Engineering
Subject: Computer Science and Engineering
Chapter: Python Programming
Keyword:
python, input, output, programming, statements, if-else, loops, print, body, done, positive, input file, output file, close, open, list, fruits, blank lines, text file, read mode, write mode