python菜单怎么做_如何编写菜单驱动的python程序

本文介绍了一个Python程序,该程序提供菜单驱动的交互方式,包括创建文件、读取文件、追加内容以及计算文件中数字的总数。用户可以输入文件名并输入整数写入文件,然后程序会读取文件内容并输出,同时可以追加新的整数到文件。此外,程序还能计算文件中数字的总数。适用Python3.3.2环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题是:

编写一个菜单驱动的Python程序,包括:从用户获取文件名并创建同名文件的函数。然后,函数应该使用while循环来处理文件,并允许用户输入要写入文件的多个整数。

使用for循环读取文件内容并将其输出到屏幕的函数。

向文件中追加若干整数的函数。

计算文件中包含的数字总数并打印

回答屏幕

这是我到目前为止所做的代码,我只需要帮助完成它:def main():

filename = input("Welcom, please enter file name:\t")

menu()

choice= int(input("Enter menu choice:\t"))

while choice != 5:

#get file choice from user

if choice == 1:

#create file

create(filename)

elif choice == 2:

#read file

read(filename)

elif choice == 3:

#append file

append(filename)

elif choice == 4:

#get total

get_total(filename)

choice = int(input("Enter menu choice:\t"))

print("\nApplication Complete")

def menu():

#user chooses a number from list

print("Choose a number to continue:\t\n\

Select 1 to create a file\n\

Select 2 to read a file\n\

Select 3 to append to a file\n\

Select 4 to calculate the total of a file\n\

Select 5 to exit programme")

def create(filename):

#open file name

outfile = open(filename,"w")

again = "y"

while again == "y":

try:

num = int(input("Input number:\t")

outfile.write(str(num)+"\n")

#asks user whether they want to continue or not

again = input("Enter y to continue:\t")

except ValueError:

print("An error occured,please enter an integer:\t")

except:

print("An undetermined error occurred")

#close file

outfile.close()

def read(filename):

read(filename)

print("\nReading File)

try:

infile = open(filename,"r")

for line in infile:

number = int(line)

print(number)

except IOError:

print("An error occured trying to read")

print("the file", filename)

except:

print("An undefined error occurred")

def append(filename):

append(filename)

print("\nAppending to file")

try:

#create file object

outfile = open(filename, "a")

again = "y"

while again == "y":

try:

num = int(input("input number to append to file:\t"))

outfile.write(str(num)+"\n")

again = input ("enter y to continue:\t")

except ValueError:

print("an error occured please an integer")

except:

print("an undefined error occured")

except IOError:

print("an error occurred trying to read")

print("the file", filename)

except:

print("an undefined error occurred")

infile.close()

#call main

main()

它一直说,create函数中有一个无效语法。另外,有人能帮我写一个函数,计算文件中包含的数字总数,并将答案打印到屏幕上吗?我正在使用Python3.3.2。

好的,我让代码正常工作了,我只需要编写一个函数来计算文件中包含的数字总数,并将答案打印到屏幕上,如果有人需要帮助,请完成它

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值