2015-11-11 117 views
1

我想按字母順序排列變量「infofile」內的文件。我目前的代碼不能工作,文件保持不變。該程序本身是一個基本調查問卷,用於實驗讀取和寫入文件。在Python中按字母順序對文本文件的內容進行排序

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() 

在此先感謝。

+0

什麼infofile看起來像現在,什麼應該看起來排序時是怎樣的? – hd1

回答

0

你忘了到排序的線寫回文件:

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

嗨,我試着用你的行寫回文件,但shell返回一個類型錯誤,指出「TypeError:write()參數必須是str,而不是列表」。 (43行)。如果你能幫助我,這將不勝感激。 – Delta

+0

@Delta修復它 – Sebastian

相關問題