| 215 | |
| 216 | |
| 217 | class Writer(): |
| 218 | def __init__(self, fileobj, dialect='excel', **fmtparams): |
| 219 | if fileobj is None: |
| 220 | raise TypeError('fileobj must be file-like, not None') |
| 221 | |
| 222 | self.fileobj = fileobj |
| 223 | |
| 224 | if isinstance(dialect, str): |
| 225 | dialect = get_dialect(dialect) |
| 226 | |
| 227 | try: |
| 228 | self.dialect = Dialect.combine(dialect, fmtparams) |
| 229 | except Error as e: |
| 230 | raise TypeError(*e.args) |
| 231 | |
| 232 | strategies = { |
| 233 | QUOTE_MINIMAL: QuoteMinimalStrategy, |
| 234 | QUOTE_ALL: QuoteAllStrategy, |
| 235 | QUOTE_NONNUMERIC: QuoteNonnumericStrategy, |
| 236 | QUOTE_NONE: QuoteNoneStrategy, |
| 237 | } |
| 238 | self.strategy = strategies[self.dialect.quoting](self.dialect) |
| 239 | |
| 240 | def writerow(self, row): |
| 241 | if row is None: |
| 242 | raise Error('row must be an iterable') |
| 243 | |
| 244 | row = list(row) |
| 245 | only = len(row) == 1 |
| 246 | row = [self.strategy.prepare(field, only=only) for field in row] |
| 247 | |
| 248 | line = self.dialect.delimiter.join(row) + self.dialect.lineterminator |
| 249 | return self.fileobj.write(line) |
| 250 | |
| 251 | def writerows(self, rows): |
| 252 | for row in rows: |
| 253 | self.writerow(row) |
| 254 | |
| 255 | |
| 256 | START_RECORD = 0 |