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): ')
解决方案
正如@jonrsharpe 作为评论指出的那样,问题是您在下面的语句中明确关闭了文件:
for record in range(5):file.write("New "+str(record)+"\n") and file.close()
“f.write(string) 将字符串的内容写入文件,返回写入的字符数。”
因此,当您写入文件时,它会返回一个不同于零的数字,“和”运算符将其用作“ True ”值。因为第一个值为“True”,所以计算第二个表达式“ file.close() ”并关闭文件。因此,在下一次迭代中,它会尝试写入不再打开的文件,并且您会收到错误消息。
推荐阅读
- laravel - Laravel Livewire:访问和操作哈希 URI
- java - 在 Java Cup 中的状态中发现 Shift/Reduce 冲突
- angular - 自定义角度表单组件中的触发更改事件
- c++ - 打印要选择的两个元素的功率总和
- reactjs - react-quilljs 和 reactjs-popup 不能一起工作
- javascript - Javascript没有验证是否输入了特殊字符
- reactjs - 为什么导入特定组件会导致捆绑包中的整个库?
- node.js - 从 Postgres Sql 中检索数据并在日期选择器中显示
- docker - 如何运行 nginx docker 底层 docker-entrypoint.sh
- c# - ASP.NET Core Controller 返回的 ViewResult 消耗在哪里?