以'a+'模式打开文件无法读取,附Python Database类相关代码
解决以'a+'模式打开文件无法读取内容的问题
嘿,我一眼就看出问题出在哪了——你用a+模式打开文件后,文件指针默认停在文件末尾,这时候直接用csv.DictReader去读,当然读不到任何内容啦!
问题根源
a+模式的特性是:打开文件用于读取和追加,文件打开时,指针会被放在文件的末尾。这意味着如果不调整指针位置,后续的读取操作会从末尾开始,自然读不到已有内容。
解决方案:调整文件指针位置
在初始化csv.DictReader之前,调用file.seek(0)将指针移到文件开头,这样就能正常读取文件内容了。同时,还要注意追加内容后指针会回到末尾,后续读取时需要再次调整指针。
修改后的完整代码
import csv class Database(): # 替换成你实际的字段名 __FIELDNAMES = ['id', 'name', 'email'] def __init__(self, db_filename, *args, **kwargs): self._db_file = open(db_filename, 'a+', newline='') self._csv_writer = csv.DictWriter( self._db_file, fieldnames=self.__FIELDNAMES) # 关键:将文件指针移到文件开头,才能读取已有内容 self._db_file.seek(0) self._csv_reader = csv.DictReader( self._db_file, fieldnames=self.__FIELDNAMES) # 可选:如果文件是空的,写入表头 self._db_file.seek(0, 2) # 移回末尾准备追加 if self._db_file.tell() == 0: self._csv_writer.writeheader() def save(self, data): # 追加数据前确保指针在末尾(可选,因为a+模式写入默认在末尾) self._db_file.seek(0, 2) self._csv_writer.writerow(data) # 立即刷新到磁盘,避免数据丢失 self._db_file.flush() def get_all_records(self): # 读取前必须将指针移到开头 self._db_file.seek(0) # 重新创建reader,因为之前的reader可能已经读完了所有内容 self._csv_reader = csv.DictReader( self._db_file, fieldnames=self.__FIELDNAMES) return list(self._csv_reader) # 资源清理:关闭文件 def close(self): if not self._db_file.closed: self._db_file.close() # 实现上下文管理器,支持with语句自动关闭 def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close()
额外说明
- 关于
csv.DictReader的复用:一旦csv.DictReader读完一次文件,它的内部指针就会停在末尾,再次调用它不会重新读取,所以每次读取前最好重新创建DictReader实例(或者重置指针后重新初始化)。 - 文件资源管理:一定要记得关闭文件,或者使用
with语句来自动管理,避免资源泄漏:with Database('mydb.csv') as db: db.save({'id': '1', 'name': 'Alice', 'email': 'alice@example.com'}) records = db.get_all_records() print(records)
内容的提问来源于stack exchange,提问作者Maxim Kolodnikov
相关产品推荐
相关产品推荐

