Code

*** empty log message ***
[roundup.git] / roundup / rcsv.py
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.
5 """
7 from roundup.i18n import _
8 from cStringIO import StringIO
9 error = """Sorry, you need a module compatible with the csv module.
10 Either upgrade your Python to 2.3 or later, or get and install
11 the csv module from:
12 http://www.object-craft.com.au/projects/csv/
14 These two csv modules are different but Roundup can use either.
15 """
16 try:
17     import csv
18     try:
19         _reader = csv.reader
20         writer = csv.writer
21         excel = csv.excel
22         error = ''
23     except AttributeError:
24         # fake it all up using the Object-Craft CSV module
25         class excel:
26             pass
27         if hasattr(csv, 'parser'):
28             error = ''
29             def _reader(fileobj, dialect=excel):
30                 # note real readers take an iterable but 2.1 doesn't
31                 # support iterable access to file objects.
32                 result = []
33                 p = csv.parser(field_sep=dialect.delimiter)
35                 while 1:
36                     line = fileobj.readline()
37                     if not line: break
38  
39                     # parse lines until we get a complete entry
40                     while 1:
41                         fields = p.parse(line)
42                         if fields: break
43                         line = fileobj.readline()
44                         if not line:
45                             raise ValueError, "Unexpected EOF during CSV parse"
46                     result.append(fields)
47                 return result
48             class writer:
49                 def __init__(self, fileobj, dialect=excel):
50                     self.fileobj = fileobj
51                     self.p = csv.parser(field_sep = dialect.delimiter)
52                 def writerow(self, fields):
53                     print >>self.fileobj, self.p.join(fields)
54                 def writerows(self, rows):
55                     for fields in rows:
56                         print >>self.fileobj, self.p.join(fields)
58 except ImportError:
59     class excel:
60         pass
61        
62 class colon_separated(excel):
63     delimiter = ':' 
64 class comma_separated(excel):
65     delimiter = ',' 
67 def reader(fileobject, dialect=excel):
68     csv_lines = [line for line in fileobject.readlines() if line.strip()]
69     return _reader(StringIO(''.join(csv_lines)), dialect)
71 if __name__ == "__main__":
72     f=open('testme.txt', 'r')
73     r = reader(f, colon_separated)
74     remember = []
75     for record in r:
76         print record
77         remember.append(record)
78     f.close()
79     import sys
80     w = writer(sys.stdout, colon_separated)
81     w.writerows(remember)