简体   繁体   English

在Python中按字母顺序对文本文件的内容进行排序

[英]Sorting contents of a text file alphabetically in Python

I would like to alphabetically sort the file inside the variable 'infofile'. 我想按字母顺序对文件'infofile'中的文件进行排序。 My current code to do this does not work, with the file remaining untouched. 我当前执行此操作的代码无法正常工作,文件保持不变。 The program itself is a basic questionnaire, created to experiment reading and writing to files. 该程序本身是一个基本的调查表,旨在对文件的读写进行实验。

import time
import sys

name = input("What is your first name?").upper()

age = input("How old are you?")
while not age.isdigit():
    print("Please Only Enter Numbers.")
    age = input("How old are you?")

if int(age) <16:
    infofile = "DatabaseMinor.txt"
elif int(age) >15 and int(age) <22:
    infofile = "DatabaseYoungAdult.txt"
elif int(age) >21 and int(age) <65:
    infofile = "DatabaseAdult.txt"
else:
    infofile = "DatabaseSenior.txt"

gender = input("Are you [M]ale or [F]emale?").upper()
while gender not in {'M', 'F'}:
    print("Please Only Enter M Or F.")
    gender = str(input("Are you [M]ale or [F]emale?")).upper()

location = input("What country are you from? (UK)").upper()
while location not in {'ENGLAND', 'SCOTLAND', 'WALES', 'NORTHERN IRELAND'}:
      print("Please Only Enter A Valid Country Within The UK.")
      location = input("What country are you from?").upper()

#Compilation of inputs into a single line format
userinfo = name + " " + str(age) + " " + gender + " " + location + " " + (time.strftime("%d/%m/%Y")) + " " + (time.strftime("%H:%M:%S")) + '\n'

#Opening and writing value of the userinfo variable to the appropriate text file
file = open(infofile, 'a')
file.write(userinfo)
file.close()

file = open(infofile)
lines = file.readlines()
lines.sort()
file.close()

Thanks in advance. 提前致谢。

You're forgetting to write the sorted lines back to the file: 您忘记将已排序的行写回到文件中:

file = open(infofile)
lines = file.readlines()
lines.sort()
for line in lines:
    file.write(line)   # <-- Write the lines back
file.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM