我是一個自學的程式員,我試圖用 Python 制作一個票務系統,它接受多個輸入并根據票證數量從檔案中讀取。但是,以前的輸入被較新的輸入覆寫,我似乎無法修復它。
我得到的輸出是這樣的:
J
a
k
e
25
M
a
l
e
但我希望輸出看起來像這樣:
Jake;25;Male
我在下面附上了這個程式的代碼。任何幫助將不勝感激。謝謝你。
import sys, select, os
from os import system
def option_1():
with open(input("Input file name with extension: "), 'w ') as f:
people = int(input("\nHow many tickets: "))
name_l = []
age_l = []
sex_l = []
for p in range(people):
name = str(input("\nName: "))
name_l.append(name)
age = int(input("\nAge: "))
age_l.append(age)
sex = str(input("\nGender: "))
sex_l.append(sex)
f.flush()
for item in name:
f.write("%s\n" %item)
for item in [age]:
f.write("%s\n" %item)
for item in sex:
f.write("%s\n" %item)
x=0
print("\nTotal Ticket: ", people, '\n')
for p in range(1, people 1):
print("Ticket No: ", p)
print("Name: ", name)
print("Age: ", age)
print("Sex: ", sex)
x = 1
def option_2():
with open(input('Input file name with extension: '), 'r') as f:
fileDir = os.path.dirname(os.path.realpath('__file__'))
f.flush()
f_contents = f.read()
print("\n")
print(f_contents, end = '')
def main():
system('cls')
print("\nTicket Booking System\n")
print("\n1. Ticket Reservation")
print("\n2. Read")
print("\n0. Exit Menu")
print('\n')
while True:
option = int(input("Choose an option: "))
if option < 0 or option > 2:
print("Please choose a number according to the menu!")
else:
while True:
if option == 1:
system('cls')
option_1()
user_input=input("Press ENTER to return to main menu: \n")
if((not user_input) or (int(user_input)<=0)):
main()
elif option == 2:
system('cls')
option_2()
user_input=input("Press ENTER to return to main menu: \n")
if((not user_input) or (int(user_input)<=0)):
main()
else:
exit()
if __name__ == "__main__":
main()
uj5u.com熱心網友回復:
如果您有最新版本的 python,您可以使用 anf-string來撰寫您需要的格式。
您需要一個回圈來迭代您收集的資訊。
你可能只需要這個:
...
f.flush()
for name,age,sex in zip(name_l, age_l, sex_l):
f.write(f"{name};{age};{sex}\n")
...
此外,控制臺的列印輸出需要類似的回圈:
print("\nTotal Ticket: ", people, '\n')
for p,(name,age,sex) in enumerate(zip(name_l, age_l, sex_l), start = 1):
print("Ticket No: ", p)
print("Name: ", name)
print("Age: ", age)
print("Sex: ", sex)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/318437.html
