如何将文件本地存储到类中?

How to store file locally to a class?

我有一个 class 应该能够从 .csv 文件中读取数据。在 class 的 __init__ 中,我读取文件并将其作为 self.csv_table 在本地存储到 class。问题是当我尝试在另一个函数中访问这个变量时,我得到了 ValueError: I/O operation on closed file。我怎样才能避免这个错误,而是打印文件?


import csv


class CsvFile(object):
    """
    A class that allows the user to read data from a csv file. Can read columns, rows, specific fields
    """
    def __init__(self, file, delimiter="'", quotechar='"'):
        """
        file: A string. The full path to the file and the file. /home/user/Documents/table.csv
        delimter & quotechar: Strings that define how the table's rows and columns are constructed
        return: the file in a way use-able to other functions
        Initializes the csv file
        """
        with open(file, 'r') as csv_file:
            self.csv_table = csv.reader(csv_file, delimiter=delimiter, quotechar=quotechar)  # local copy of csv file

    def read_csv(self):
        """
        Prints the csv file in a simple manner. Not much can be done with this.
        """
        for row in self.csv_table:
            print(', '.join(row))

my_file = CsvFile(file)
my_file.read_csv()  # this one causes an I/O error

在这里,您的问题是 self.csv_table 包含文件引用本身,而不是文件内容。退出 "with" 语句后,文件将关闭,您将无法再访问它。

由于您关心内容,因此需要通过迭代 csv_reader 将您的内容存储在 csv_table 中,例如在您的 __init__ 函数中,您可以执行类似这个:

def __init__(self, file, delimiter="'", quotechar='"'):
    """
    file: A string. The full path to the file and the file. /home/user/Documents/table.csv
    delimter & quotechar: Strings that define how the table's rows and columns are constructed
    return: the file in a way use-able to other functions
    Initializes the csv file
    """
    self.csv_table = []
    with open(file, 'r') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=delimiter, quotechar=quotechar)  # local copy of csv file
        for data_entry in csv_reader:
            self.csv_table.append(data_entry)

然后您将能够以列表的形式访问self.csv_table中的内容。

或者,如果您真的很在意该文件,则需要随时重新打开它 => 将 self.csv_table 更改为 self.csv_filename,然后在 read_csv 函数中,您只需重新打开文件并在需要时随时创建 reader =>

import csv


class CsvFile(object):
    """
    A class that allows the user to read data from a csv file. Can read columns, rows, specific fields
    """
    def __init__(self, filename, delimiter="'", quotechar='"'):
        """
        filename: A string. The full path to the file and the file. /home/user/Documents/table.csv
        delimter & quotechar: Strings that define how the table's rows and columns are constructed
        return: the file in a way use-able to other functions
        Initializes the csv file
        """
        self.filename = filename
        self.delimiter = delimiter
        self.quotechar = quotechar

    def read_csv(self):
        """
        Prints the csv file in a simple manner. Not much can be done with this.
        """
        with open(self.filename, 'r') as csv_file:
            csv_table = csv.reader(csv_file, delimiter=self.delimiter, quotechar=self.quotechar)  
            for row in csv_table:
                print(', '.join(row))

my_file = CsvFile(file)
my_file.read_csv()  # this one causes an I/O error