简体   繁体   中英

How to trim leading and trailing whitespaces in csv file?

hi wanna to remove leading and trailing spaces in csv files

24333,   116,    47,MCD,00000000000000000017996,   112
24333,   116,    47,MCD,00000000000000610036485,   112  
24333,   116,    47,MCD,00000000000000610036485,   112

can any one help the code i tried

import csv

csvfile= open('strip.csv','r')
csvfile1= open('strip11.csv','w') 
stripped = (row.strip() for row in csvfile)
reader = csv.reader(stripped,delimiter=' ')
writer= csv.writer(csvfile1)
for row in reader:
   writer.writerow(row)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM