我正在编写一个模块,可以在几种不同的文件格式之间进行转换(例如vhdl到verilog,excel表到vhdl等)。它不是那么难,但有很多语言特定的格式要做。我刚刚想到,一个优雅的方法是通过在file.io上构建一个类来为每种文件格式类型提供类类型。该类将继承文件的方法,但也能够读取或写入该文件的特定语法。我找不到任何文件io超类的例子以及如何编写它。我的想法是实例化它(打开文件)我可以使用:
my_lib_file = Libfile(filename, 'w')
并将一个简单的参数写入libfile我可以使用像
这样的东西my_lib_file.simple_parameter(param, value)
这样的类会将我目前拥有的许多文件特定功能整合在一起。实际上我更希望能够将类实例化为with语句的一部分,例如:
with Libfile(filename, 'w') as my_lib_file:
for param, value in my_stuff.items():
my_lib_file.simple_parameter(param, value)
答案 0 :(得分:3)
这是错误的思考方式。
您继承以便重复使用。基类提供了其他人可以使用的接口。对于类似文件的对象,它主要是db.TransactionDetails.aggregate([
{$group:{_id:{"CITY" : "$cityName"},uniqueCount: {$addToSet: "$emailId"}}},
{$project:{"CITY":1,uniqueCustomerCount:{$size:"$uniqueCount"}} }
]);
和read
。但是,您只想调用另一个函数write
。直接调用simple_parameter
可能会破坏格式。
真的你不希望它成为类似文件的对象。您希望在用户调用write
时写入文件。实现应该委托给类似成员文件的对象,例如:
simple_parameter
这很容易测试,因为您可以传递支持class LibFile:
def __init__(self, file):
self.file = file
def simple_parameter(self, param, value):
self.file.write('{}: {}\n'.format(param, value))
的任何内容:
write
编辑:
如果您真的希望该类管理文件的生命周期,您可以提供一个close函数并使用closing
上下文管理器:
>>> import sys
>>> lib = LibFile(sys.stdout)
>>> lib.simple_parameter('name', 'Stephen')
name: Stephen
用法:
class Formatter:
def __init__(self, filename, mode):
self.file = open(filename, mode)
def close(self):
self.file.close()
第二次编辑:
如果您不想使用closing
,您可以编写自己的上下文管理器:
class LibFormatter(Formatter):
def simple_parameter(self, param, value):
self.file.write('{}: {}\n'.format(param, value))
from contextlib import closing
with closing(LibFormatter('library.txt', 'w')) as lib:
... # etc
用法:
class ManagedFile:
def __init__(self, filename, mode):
self.file = open(filename, mode)
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def close(self):
self.file.close()
答案 1 :(得分:0)
我的两行解决方案如下:
/usr/include/openssl/ui.h
类初始化如下:
with open(lib_loc + '\\' + lib_name + '.lib', 'w') as lib_file_handle:
lib_file = Liberty(lib_file_handle)
# do stuff using lib_file
现在不是传递原始文件句柄而是将类和函数一起传递给我的函数。
最简单的功能是:
def __init__(self, file):
''' associate this instance with the given file handle '''
self.f = file
这意味着我正在复制file.io类中内置的write函数。这就是我试图避免的。
答案 2 :(得分:0)
我现在找到了一种令人满意的方式来做我想做的事。以下是我的基类,它基于file_io的基函数(但不是子类),也是编写CSV文件的简单示例。我也有HTML,Verilog和其他格式器。代码是:
class Formatter():
''' base class to manage the opening of a file in order to build classes which write a file
with a specific format so as to be able to pass the formatting functions to a subroutine
along with the file handle
Designed to use with "with" statement and to shorten argument lists of functions which use
the file
'''
def __init__(self, filename):
''' associate this instance with the given file handle
'''
self.f = open(filename, 'w')
def wr(self, line, end='\n'):
''' write line given to file
'''
self.f.write(line + end)
def wr_newline(self, num):
''' write num newlines to file
'''
self.f.write('\n'*num)
def __enter__(self):
''' needed for use with with statement
'''
return self
def __exit__(self, *args):
''' needed for use with with statement
'''
self.close()
def close(self):
''' explicit file close for use with procedural progamming style
'''
self.f.close()
class CSV(Formatter):
''' class to write items using comma separated file format string formatting
inherrits:
=> wr(line, end='\n'):
=> wr_newline(n):
all file io functions via the self.f variable
'''
@staticmethod
def pp(item):
''' 'pretty-print - can't have , or \n in strings used in CSV files
'''
return str(item).replace('\n', '/').replace(',', '-')
def __init__(self, filename):
'''open filen given as a CSV file
'''
super().__init__(filename + '.csv')
def wp(self, item):
''' write a single item to the file
'''
self.f.write(self.pp(item)+', ')
def ws(self, itemlist):
''' write a csv list from a list variable
'''
self.wr(','.join([self.pp(item) for item in itemlist]))