首页 > 解决方案 > 有没有办法在没有文件对象的情况下关闭 python 中的文件?

问题描述

我无法关闭此文件,因为该文件直接输入到“行”列表中。

我试过用命令行关闭。关闭()但它不起作用。

def readfile():
    lines = [line.rstrip('\n') for line in open('8ballresponses.txt', 'r')]  
    print(random.choice(lines))

我没有收到错误,但我希望能够关闭文件。

标签: python

解决方案


而不是file对象,lines是 a list,所以你不能关闭它。您应该使用变量存储文件对象open('8ballresponses.txt', 'r'),以便稍后关闭它:

def readfile(file_path):
    test_file = open(file_path, 'r')
    lines = [line.rstrip('\n') for line in test_file]
    test_file.close()
    print(random.choice(lines))

或者简单地使用with“在没有文件对象的情况下关闭 python 中的文件”:

def readfile(file_path):
    with open(file_path, 'r') as test_file:
        lines = [line.rstrip('\n') for line in test_file]
        print(lines)

推荐阅读