我对编程和 python 都很陌生。我需要读取文件中的列表,使用 while 循环或 for 循环对该列表按字母顺序排列,然后将按字母顺序排列的列表写入第二个文件。文件未排序,也未写入文件。欢迎任何见解或建设性的批评。
unsorted_list = open("unsorted_list.txt", "r") #open file congaing list
sorted_list = open ("sorted_list.txt", "w") #open file writing to
usfl = [unsorted_fruits.read()] #create variable to work with list
def insertion_sort(list): #this function has sorted other list
for index in range(1, len(list)):
value = list[index]
i = index - 1
while i >= 0:
if value < list[i]:
list[i+1] = list[i]
list[i] = value
i = i - 1
else:
break
insertion_sort(usfl) #calling the function to sort
print usfl #print list to show its sorted
sfl = usfl
sorted_furits.write(list(sfl)) #write the sorted list to the file
unsorted_fruits.close()
sorted_fruits.close()
exit()