修剪csv文件中的前导和尾随空格

时间:2016-01-18 15:10:30

标签: python csv

您想删除csv文件中的前导和尾随空格

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

任何人都可以帮助我尝试的代码

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)

1 个答案:

答案 0 :(得分:4)

魔术来自于对每行记录中的每个项目应用strip

通常像" abc ".strip一样剥离字符串。要在没有实际字符串的情况下引用strip方法,可以import string然后使用string.strip

map(string.strip, list_of_strings_to_strip)strip应用于记录中的每个项目,并将其返回到列表中。

>>> import string
>>> rec = ["  a  ", "  b  ", "  c  "]
>>> map(string.strip, rec)
["a", "b", "c"]

您数据的完整工作示例:

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))

with open(...是所谓的上下文管理器,确保创建的文件描述符将被关闭,而不管内部块执行期间可能的失败。

结果文件如下:

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