我需要按時間順序對這些資料進行排序,希望是按日期和按時間排序,但現在我只想按日期對它進行排序……資訊在 TXT 檔案中:
2022/5/10 at 10 the client Mari has appointment with the Dra. Windrunner
2022/1/5 at 2 the client Ian has appointment with the Dr. Stark
2022/1/4 at 10 the client Amy has appointment with the Dra. Windrunner
2022/1/5 at 2 the client Josh has appointment with the Dr. Stark
2022/2/22 at 5 the client Mike has appointment with the Dr. Pool
2022/2/22 at 4 the client Pedro has appointment with the Dr. Stark
這是我現在的代碼:
Docs = ("Dr. Stark", "Dra. Windrunner", "Dr. Pool")
x = 0
loop = False
DocsConverter = {
"0" : "Dr. Stark",
"1" : "Dra. Windrunner",
"2" : "Dr. Pool",
"dr. stark": "Dr. Stark",
"dra. windrunner" : "Dra. Windrunner",
"dr. pool" : "Dr. Pool",
"stark" : "Dr. Stark",
"windrunner" : "Dra. Windrunner",
"pool" : "Dr. Pool"
}
with open("appointment_hospital.txt", "a") as file_ap:
pass
def menu():
option = input("select a option 1. new appointment 2.show appointments 3. Exit: (1/2/3)\n")
if option == "1":
new_appointment()
elif option == "2":
print_appointments()
elif option == "3":
file_ap.close()
exit()
else:
print("Wrong option")
def new_appointment():
global x
name_client = input("Enter the name of the client:\n")
schedule_day = input("Enter the year, month and the day of the appointment:(Y/M/D)\n")
schedule_time= input("Enter at what hour is the appointment:\n")
while x != 3:
print(f"{Docs[x]}, id = {x}")
x = 1
x = 0
which_doc = input("Enter the name or the Id of the doctor: ")
appointment_info = f"{schedule_day} at {schedule_time} the client {name_client} has appointment with the " \
f"{DocsConverter.get(which_doc)}\n"
with open("appointment_hospital.txt", "a") as file:
file.write(appointment_info)
#this is where i tried to sort the information in the txt
def print_appointments():
with open("appointment_hospital.txt", "r") as file:
lines_appointments = []
for line in file:
temp = line.split()
for i in temp:
lines_appointments.append(i)
lines_appointments.sort()
with open("sort_appointments", "w") as sort_file:
for i in lines_appointments:
sort_file.writelines(i)
sort_file.writelines(" ")
sort_file.close()
with open("sort_appointments", "w") as sort_file:
read_appointments = sort_file.read()
print(read_appointments)
while not loop:
menu()
因此,在def print_appointments():我嘗試對資料進行排序時,這是我最后一次嘗試,我所做的這些都沒有給我帶來中等積極的結果。
uj5u.com熱心網友回復:
你有一些錯誤:
- 沒有檔案擴展名
open("sort_appointments" - 按日期排序剩余按行拆分檔案
- 將串列寫入檔案時,您需要打開它以附加“a”
- 讀取檔案時,必須輸入字母“r”
def print_appointments():
with open("appointment_hospital.txt", "r") as file:
lines_appointments = []
for line in file:
lines_appointments.append(line)
lines_appointments.sort()
with open("sort_appointments.txt", "a") as sort_file:
sort_file.writelines(lines_appointments)
with open("sort_appointments.txt", "r") as sort_file:
read_appointments = sort_file.read()
print(read_appointments)
print_appointments()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/485225.html
上一篇:計算嵌套串列中串列元素的出現次數
