Code

documentation cleanup
[roundup.git] / roundup / rcsv.py
1 """Supplies a Python-2.3 Object Craft csv module work-alike to the extent
2 needed by Roundup using the Python 2.3 csv module.
3 """
4 __docformat__ = 'restructuredtext'
6 from roundup.i18n import _
7 from cStringIO import StringIO
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/
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)
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)
57 except ImportError:
58     class excel:
59         pass
60        
61 class colon_separated(excel):
62     delimiter = ':' 
63 class comma_separated(excel):
64     delimiter = ',' 
66 def reader(fileobject, dialect=excel):
67     csv_lines = [line for line in fileobject.readlines() if line.strip()]
68     return _reader(StringIO(''.join(csv_lines)), dialect)
70 if __name__ == "__main__":
71     f=open('testme.txt', 'r')
72     r = reader(f, colon_separated)
73     remember = []
74     for record in r:
75         print record
76         remember.append(record)
77     f.close()
78     import sys
79     w = writer(sys.stdout, colon_separated)
80     w.writerows(remember)