The magic comes from applying strip
on each item in each row record.
Stripping a string is done usually like " abc ".strip
. To refer to the strip
method without having actual string at hand, one can import string
and then use string.strip
.
The map(string.strip, list_of_strings_to_strip)
applies the strip
to each item in the record and returns them in a list.
>>> import string
>>> rec = [" a ", " b ", " c "]
>>> map(string.strip, rec)
["a", "b", "c"]
The complete working example for your data:
import csv
import string
with open("data.csv") as f:
reader = csv.reader(f, delimiter=",")
with open("stripped.csv", "w") as fo:
writer = csv.writer(fo)
for rec in reader:
writer.writerow(map(string.strip, rec))
The with open(...
are so called context managers ensuring, that the created file descriptor will get closed regardless of possible failure during the inner block execution.
Resulting file looks like:
24333,116,47,MCD,00000000000000000017996,112
24333,116,47,MCD,00000000000000610036485,112
24333,116,47,MCD,00000000000000610036485,112