本文整理汇总了Python中django.utils.six.moves.cStringIO.truncate方法的典型用法代码示例。如果您正苦于以下问题:Python cStringIO.truncate方法的具体用法?Python cStringIO.truncate怎么用?Python cStringIO.truncate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.six.moves.cStringIO
的用法示例。
在下文中一共展示了cStringIO.truncate方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: UnicodeWriter
# 需要导入模块: from django.utils.six.moves import cStringIO [as 别名]
# 或者: from django.utils.six.moves.cStringIO import truncate [as 别名]
class UnicodeWriter(object):
"""Convert a two-dimensional data structure into a UTF-8-encoded CSV byte
string. Inspired by <http://docs.python.org/library/csv.html#examples>.
"""
# FixMe: This must go when dropping support for Python 2.
def __init__(self, stream=None, dialect=csv.excel_tab, encoding="utf-8", **kwargs):
"""Additional keyword arguments are passed to the
``csv.writer`` factory function in Python's ``csv`` module. After
having instantiated this class, you can use `writerow` and `writerows`
to add data to it, and then extract it in the CSV format using
`getvalue`.
:param stream: the writable file-like object where the output should be
sent; if ``None``, you must get the outout with `getvalue`.
:param dialect: the CSV format; it defaults to Excel's TAB format
(TAB-separated, double-quotes)
:param encoding: name of the output encoding to be used; defaults to
UTF-8
:type stream: file
:type dialect: ``csv.Dialect``
:type encoding: str
"""
import codecs
self.queue = StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwargs)
self.stream = stream if stream else StringIO()
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
"""Add the given row to the output.
:param row: list of the table cells
:type row: list of object
"""
output_row = []
for s in row:
if s is None:
output_row.append("")
else:
output_row.append(six.text_type(s).encode("utf-8"))
self.writer.writerow(output_row)
data = self.queue.getvalue()
data = data.decode("utf-8")
data = self.encoder.encode(data)
self.stream.write(data)
self.queue.truncate(0)
def writerows(self, rows):
"""Add the given rows to the output.
:param rows: list of rows; each row is a list of table cells
:type rows: list of list of object
"""
for row in rows:
self.writerow(row)
def getvalue(self):
"""Get the output so far. Normally, you will call this method after
the instance was filled with all data. Thus, after called this method,
the instance of ``UnicodeWriter`` is no longer used.
:return:
the table in CSV format, as an encoded octet string
:rtype: str
"""
return self.stream.getvalue()