python - Python 中的崩溃或 ErrorValue - 关闭文件

标签 python file valueerror open-closed-principle

我有一个类,其中包含我们的所有数据,在这里我通过以下方式打开一个文件:

carIn= open("dataIn.txt","w")
carOut= open("dataUit.txt","w")

在另一个类(class)中,我有一个主程序循环。我在循环中关闭了文件,但它不会再次打开。如果我在循环外关闭它,整个程序就会崩溃。这是我的代码:

while startScreen.getstopt() == False:

    startScreen.start()
    print("screen start")

    screen = Screen(wereld.getIntersection())
    startSimulatiion()
    print("Simulatiion start:")

    for x in Files.listIn:
        Files.carIn.write(str(x) + "\n")

    for x in Files.listOut:
        Files.carOut.write(str(x) +"\n")


    result= Resultaten()
    Files.calculatedRatio= result.calculateRatio()
    print(Files.calculatedRatio)

    if screen.startScreen == True:
        Files.carIn.write("\n")
        Files.carIn.write("\n")
        Files.carIn.write("\n")
        Files.carOut.write("\n")
        Files.carOut.write("\n")
        Files.carOut.write("\n")

    Files.carIn.close()
    Files.carOut.close()

最佳答案

在我看来,你不应该持有 open要传递的类/实例变量中的对象。这会变得困惑并且很容易忘记close明确地。

相反,我会将文件名保存在变量中,并将它们传递到 open 的函数中。和close文件通过with声明。

这是一个例子:

Files.carIn = 'dataIn.txt'
Files.carOut = 'dataUit.txt'

with open(Files.carIn, 'w') as file_in, open(Files.carOut, 'w') as file_out:
    while startScreen.getstopt() == False:
        # do things with file_in & file_out

关于python - Python 中的崩溃或 ErrorValue - 关闭文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50306952/

相关文章:

c - 在 C 中编辑/修改和删除随机访问文件中的记录

python - 当我不在我的 Django 博客文章中上传图片时防止出现 ValueError

Python:逻辑回归给出 ValueError:未知标签类型: 'continuous'

python - ValueError:无法将字符串转换为 float : '.'

python - 使用 SQLAlchemy 管理数据库迁移的方法?

python - 使用 Pyautogui 实现 Excel 自动化

java - System.getProperty ("user.home") 在 Tomcat 上返回 "/usr/share/tomcat7/"

python - 如何使用 Python 的 'unittest' 对写入文件的函数进行单元测试

Python urllib2 返回一个空字符串

python - Pandas :用条件替换列中的值