2

我正在学习教科书中的教程,“从 python 2nd edition 开始”,并且我在 IDLE 3.2 中得到了这个练习的回溯。我似乎无法弄清楚这个问题,它允许我输入销售数量,然后只有 1 个销售量,它会回显“写入 sales.txt 的数据”。然后显示第 2 天的提示,但输入的任何数量都会导致回溯:

第 118 行,在 main sales_file.write(str(sales) + '\n') ValueError: I/O operation on closed file。

代码:

def main():

     num_days = int(input('For how many days do ' + \
                          'you have sales? '))

     sales_file = open('sales.txt', 'w')


     for count in range(1, num_days + 1):
         sales = float(input('Enter the sales for day #' + \
                             str(count) + ': '))
         sales_file.write(str(sales) + '\n')
         sales_file.close()
         print('Data written to sales.txt.')

main()
4

3 回答 3

7

您正在关闭 for 循环内的文件。下次写入文件时通过循环,您正在尝试写入已关闭的文件,因此错误消息显示I/O operation on closed file..

移动线

sales_file.close()

to 在 for 循环底部的 print 语句之后,但在for. 这只会在循环后关闭文件一次(而不是重复),即当您在程序结束时完成它时。

像这样:

for count in range(1, num_days + 1):
   sales = float(input('Enter the sales for day #' + str(count) + ': '))
   sales_file.write(str(sales) + '\n')
   print('Data written to sales.txt.')

sales_file.close()   # close file once when done

更好的方法是使用该with语句,因为它会在您完成后自动为您关闭文件。所以你可以说

with open('sales.txt', 'w') as sales_file:
   for count in range(1, num_days + 1)
      # rest of the code
      # but *no* close statement needed.
于 2012-05-14T01:53:07.580 回答
1

with open('sales_file','w') 如果您在离开块后使用这种方式,您可以以更简洁的方式执行此操作,with它将自动关闭文件。所以你会编辑你的函数来阅读:

def main():

    num_days = int(input('For how many days do ' + \
                        'you have sales? '))

    with open('sales.txt', 'w') as sales_file:
        for count in range(1, num_days + 1):
            sales = float(input('Enter the sales for day #' + \
                                str(count) + ': '))
            sales_file.write(str(sales) + '\n')
            print('Data written to sales.txt.')
    # once you leave the block (here) it automatically closes sales_file
main()
于 2012-05-14T02:00:17.253 回答
0

您在 1 个循环中关闭文件,然后在下一次迭代中写入它。将 close 放在循环之外

def main():

     num_days = int(input('For how many days do ' + \
                          'you have sales? '))

     sales_file = open('sales.txt', 'w')


     for count in range(1, num_days + 1):
         sales = float(input('Enter the sales for day #' + \
                             str(count) + ': '))
         sales_file.write(str(sales) + '\n')
         print('Data written to sales.txt.')

     sales_file.close()

main()

更好的是,您可以使用with

def main():

     num_days = int(input('For how many days do you have sales? '))

     with open('sales.txt', 'w') as sales_file:

         for count in range(1, num_days + 1):
             sales = input('Enter the sales for day #%s: ' % count)
             sales_file.write('%s\n' % sales)
             print('Data written to sales.txt.')

main()
于 2012-05-14T01:53:46.773 回答