首页 > 解决方案 > 函数,文件处理

问题描述

我制作了这段代码,但是当我尝试追加时,我收到以下消息:

Traceback (most recent call last):
  File "main.py", line 38, in <module>
    main()
  File "main.py", line 9,in main
    elif what == 'a': append(thisFile)
  File "main.py", line 27, in append
    for record in range(5):file.write("New "+str(record)+"\n") and file.close()
ValueError: I/O operationon closed file.
    

当我尝试创建或读取文件时,结果很好,只是在我追加(或添加,如代码所示)时。怎么了?

def main():
    print("Simple text files in Python")
    thisFile = input('file name?: ')
    q = 0
    while q != 1:
      q = 1
      what = input('What do you want to do? (create, add, display): ')[:1]
      if what == 'c': create(thisFile)
      elif what == 'a': append(thisFile)
      elif what == 'd': read(thisFile)
      else: 
        print('Invalid choice, pick another: ')      
        q = 0

def create(filename):
    print("Creating file ...")
    file=open(filename,"w")
    i = 'y'
    while i == 'y':
        file.write(input('what do you want to write?') + '\n')
        i = input('one more line?(y/n): ').lower()
    file.close()

def append(filename):
    print("Adding to file ...")
    file=open(filename,"a")
    for record in range(5):file.write("New "+str(record)+"\n") and file.close()

def read(filename):
    print("Reading file ...")
    file=open(filename,"r")
    for record in file:
        text=record
        print(text)
    file.close()
do = 'y'
while do == 'y':
  main()
  do = input('Any other functions?:(y/n): ')

标签: python

解决方案


正如@jonrsharpe 作为评论指出的那样,问题是您在下面的语句中明确关闭了文件:

for record in range(5):file.write("New "+str(record)+"\n") and file.close()

文档中所述

“f.write(string) 将字符串的内容写入文件,返回写入的字符数。”

因此,当您写入文件时,它会返回一个不同于零的数字,“和”运算符将其用作“ True ”值。因为第一个值为“True”,所以计算第二个表达式“ file.close() ”并关闭文件。因此,在下一次迭代中,它会尝试写入不再打开的文件,并且您会收到错误消息。


推荐阅读