Mercurial > p > roundup > code
comparison roundup/rcsv.py @ 1767:fdaa0b751355
python2.3 CSV support, also missing thankyou in index.txt :)
| author | Richard Jones <richard@users.sourceforge.net> |
|---|---|
| date | Thu, 28 Aug 2003 04:46:54 +0000 |
| parents | |
| children | 0afdf96ea9d7 3555941caea0 |
comparison
equal
deleted
inserted
replaced
| 1765:14a2f1529759 | 1767:fdaa0b751355 |
|---|---|
| 1 """ | |
| 2 Supplies a Python-2.3 Object Craft csv module work-alike to the extent | |
| 3 needed by Roundup using the Python 2.3 csv module. | |
| 4 | |
| 5 """ | |
| 6 | |
| 7 from roundup.i18n import _ | |
| 8 error = """Sorry, you need a module compatible with the csv module. | |
| 9 Either upgrade your Python to 2.3 or later, or get and install | |
| 10 the csv module from: | |
| 11 http://www.object-craft.com.au/projects/csv/ | |
| 12 | |
| 13 These two csv modules are different but Roundup can use either. | |
| 14 """ | |
| 15 try: | |
| 16 import csv | |
| 17 try: | |
| 18 reader = csv.reader | |
| 19 writer = csv.writer | |
| 20 excel = csv.excel | |
| 21 error = '' | |
| 22 except AttributeError: | |
| 23 # fake it all up using the Object-Craft CSV module | |
| 24 class excel: | |
| 25 pass | |
| 26 if hasattr(csv, 'parser'): | |
| 27 error = '' | |
| 28 def reader(fileobj, dialect=excel): | |
| 29 # note real readers take an iterable but 2.1 doesn't | |
| 30 # support iterable access to file objects. | |
| 31 result = [] | |
| 32 p = csv.parser(field_sep=dialect.delimiter) | |
| 33 | |
| 34 while 1: | |
| 35 line = fileobj.readline() | |
| 36 if not line: break | |
| 37 | |
| 38 # parse lines until we get a complete entry | |
| 39 while 1: | |
| 40 fields = p.parse(line) | |
| 41 if fields: break | |
| 42 line = fileobj.readline() | |
| 43 if not line: | |
| 44 raise ValueError, "Unexpected EOF during CSV parse" | |
| 45 result.append(fields) | |
| 46 return result | |
| 47 class writer: | |
| 48 def __init__(self, fileobj, dialect=excel): | |
| 49 self.fileobj = fileobj | |
| 50 self.p = csv.parser(field_sep = dialect.delimiter) | |
| 51 def writerow(self, fields): | |
| 52 print >>self.fileobj, self.p.join(fields) | |
| 53 def writerows(self, rows): | |
| 54 for fields in rows: | |
| 55 print >>self.fileobj, self.p.join(fields) | |
| 56 | |
| 57 except ImportError: | |
| 58 class excel: | |
| 59 pass | |
| 60 | |
| 61 class colon_separated(excel): | |
| 62 delimiter = ':' | |
| 63 class comma_separated(excel): | |
| 64 delimiter = ',' | |
| 65 | |
| 66 | |
| 67 if __name__ == "__main__": | |
| 68 f=open('testme.txt', 'r') | |
| 69 r = reader(f, colon_separated) | |
| 70 remember = [] | |
| 71 for record in r: | |
| 72 print record | |
| 73 remember.append(record) | |
| 74 f.close() | |
| 75 import sys | |
| 76 w = writer(sys.stdout, colon_separated) | |
| 77 w.writerows(remember) | |
| 78 |
