按字母顺序将输入保存到文件

时间:2018-02-06 05:39:41

标签: python sorting alphabetical

我正在尝试编写一个python代码,它接受来自用户的一些输入并将它们放在txt1.txt中的反转字母中,但是根据输入按字母顺序排列。在我的代码中,它会将它们写入带有反转字母的文本文件,但不是按字母顺序排列。

output_file = open("txt1.txt", 'a')
while(True):
    #Reading input from user
    names=input("Enter a name or d: to finish): ")
    if(names=='d'): #exit from loop and now names are in the file.txt
        break
    #VARTOSTORETHEREVERSE
    rev_name=""
    #REVERSE THE NAMES
    for ch in names:
        rev_name =ch + rev_name


    #THISTOWRITETOFILE

    output_file.write(rev_name + '\n')


output_file.close() 

1 个答案:

答案 0 :(得分:0)

您可以创建反转名称列表并对该列表进行排序,并将其更新为输出文件,如下所示。您可以使用以下代码段:

output_file = open("txt1.txt", 'a')
names = []
while(True):
    #Reading input from user
    name = input("Enter a name or d: to finish): ")

    if(name=='d'): #exit from loop and now names are in the file.txt
        break
    else:
        #VARTOSTORETHEREVERSE
        names.append(name[::-1])

    names.sort()

#THISTOWRITETOFILE
output_file.write('\n'.join(names))
output_file.close()