I need to stripe the white spaces from a CSV file that I read
import csv aList=[] with open(self.filename, 'r') as f: reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE) for row in reader: aList.append(row) # I need to strip the extra white space from each string in the row return(aList)
Create a class based on csv. DictReader , and override the fieldnames property to strip out the whitespace from each field name (aka column header, aka dictionary key).
CSV files without whitespace is for machine (software) reading, OR where you can have a common separator that is not used elsewhere - if you want to avoid the path of escaping the separators. Fixed-width-files are better for humans, or where the separator chosen will at times be part of the text.
There's also the embedded formatting parameter: skipinitialspace (the default is false) http://docs.python.org/2/library/csv.html#csv-fmt-params
aList=[] with open(self.filename, 'r') as f: reader = csv.reader(f, skipinitialspace=False,delimiter=',', quoting=csv.QUOTE_NONE) for row in reader: aList.append(row) return(aList)
In my case, I only cared about stripping the whitespace from the field names (aka column headers, aka dictionary keys), when using csv.DictReader
.
Create a class based on csv.DictReader
, and override the fieldnames
property to strip out the whitespace from each field name (aka column header, aka dictionary key).
Do this by getting the regular list of fieldnames, and then iterating over it while creating a new list with the whitespace stripped from each field name, and setting the underlying _fieldnames
attribute to this new list.
import csv class DictReaderStrip(csv.DictReader): @property def fieldnames(self): if self._fieldnames is None: # Initialize self._fieldnames # Note: DictReader is an old-style class, so can't use super() csv.DictReader.fieldnames.fget(self) if self._fieldnames is not None: self._fieldnames = [name.strip() for name in self._fieldnames] return self._fieldnames
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With