如何修剪csv文件中的前导和尾随空格? [英] How to trim leading and trailing whitespaces in csv file?

查看:60
本文介绍了如何修剪csv文件中的前导和尾随空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

推荐答案

神奇之处在于对每个行记录中的每个项目应用 strip .

The magic comes from applying strip on each item in each row record.

通常以类似于"abc" .strip 的方式来剥离字符串.要在没有手头实际字符串的情况下引用 strip 方法,可以先导入字符串,然后再使用 string.strip .

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.

map(string.strip,list_of_strings_to_strip) 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))

具有open(...... 的称为上下文管理器,可确保创建的文件描述符将被关闭,而不考虑内部块执行期间可能发生的故障.

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.

结果文件如下:

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

这篇关于如何修剪csv文件中的前导和尾随空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆