功能、文件处理

2024-05-03 08:12:50 发布

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

我编写了这段代码,但当我尝试附加时,会收到以下消息:

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): ')

Tags: incloseinputmaindeflinefilenamerecord
1条回答
网友
1楼 · 发布于 2024-05-03 08:12:50

正如@jornsharpe所指出的,问题是您在下面的语句中明确地关闭了该文件:

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

docs中所述

"f.write(string) writes the contents of string to the file, returning the number of characters written."

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

相关问题 更多 >