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)
You can do:
There's also the embedded formatting parameter: skipinitialspace (the default is false) http://docs.python.org/2/library/csv.html#csv-fmt-params
You can create a wrapper object around your file that strips away the spaces before the CSV reader sees them. This way, you can even use the csv file with cvs.DictReader.
Then use it like this:
I hardcoded
";"
to be the delimiter. Generalising the code to any delimiter is left as an exercise to the reader.The most memory-efficient method to format the cells after parsing is through generators. Something like:
But it may be worth moving it to a function that you can use to keep munging and to avoid forthcoming iterations. For instance:
Or it can be used to factorize a class:
Read a CSV (or Excel file) using Pandas and trim it using this custom function.
You can now apply trim(CSV/Excel) to your code like so (as part of a loop, etc.)