我有一个应该能够从.csv
文件中读取数据的类。在类的__init__
中,我读取文件并将其作为self.csv_table
本地存储在类中。问题是,当我尝试在另一个函数中访问此变量时,我得到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
答案 0 :(得分:4)
这里,您的问题是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_filename更改self.csv_table,并在read_csv函数中,只需重新打开文件并随时创建阅读器=>
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