运行循环时读取文件?

2024-04-26 10:41:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难运行这个程序而不产生逻辑错误。我想知道是否有人能向我解释出什么问题。我的文件代码是:

def main():
    myfile = open('tests.txt','w')
    print('Enter six tests and scores or Enter to exit')
    print('--------------------------') #I added this feature to make the code
    #more structured
    testName = input('Enter test name: ')
    while testName != '':
        score = int(input('Enter % score of this test: ')) 
        myfile.write(str(score) + '\n')
        testName = input('Enter test name: ')  
        myfile.write(testName + '\n')
    myfile.close()
    print('File was created successfully')
main()

但是我用来读取和输出文件的代码给了我一个逻辑错误。我知道代码很快就写好了,但我不知道是怎么回事。你能检查一下我的密码并告诉我为什么它不工作吗

def main():
    myfile = open('tests.txt','r')
    print('Reading six tests and scores')
    print('Test\t               Score')
    print('----------------------------')
    test_score = 0
    counter = 0 #for number of tests
    line = myfile.readline()
    while line != '':
         name = line.rstrip('\n')
         score = int(myfile.readline())
         test_score += score
         print(name, score)
         line = myfile.readline()
         counter += 1
    myfile.close()
    average = test_score/ counter
    print('Average is',format(average,'.1f'))
main()

第一个程序的输入/输出应为
输入六个测试和分数 输入测试名称对象 在此测试中输入分数%88 输入测试名称循环 在此测试中输入%95分 输入测试名称选择 在此测试中输入分数百分比86 输入测试名称变量 在此测试中输入分数百分比82 输入测试名称文件 在此测试中输入100%分数 输入测试名称函数 在此测试中输入%80分 已成功创建文件

读取文件的第二个程序的输出应为:

阅读六个测试和分数 考试成绩 对象88 回路95 选择86 变量82 文件100 功能80 平均值为88.5


Tags: 文件代码nametest程序名称mainline
1条回答
网友
1楼 · 发布于 2024-04-26 10:41:08

你有两个问题。第一个是在write函数中while循环之前。您将测试名称作为输入,但不将其写入文件。你知道吗

在while循环之前将测试名写入文本文件可以解决第一个问题,但之后会留下另一个问题。添加新行的方式会使您在试图读取的文件末尾出现空行。将新行移到所写内容的前面。你知道吗

    testName = input('Enter test name: ')
    myfile.write(testName)
    while testName != '':
        score = int(input('Enter % score of this test: '))
        myfile.write('\n' + str(score))
        testName = input('Enter test name: ')
        myfile.write('\n' + testName)
    myfile.close()
    print('File was created successfully')

相关问题 更多 >