【问题标题】:remove space in csv file with python用python删除csv文件中的空间
【发布时间】:2021-11-09 07:24:36
【问题描述】:

我有一个 csv 文件,例如:

id ,age ,type ,destination
1,10,20     ,Paris
   
2,20,50      ,Canada
3,10,23     ,London

在类型和目标值之后我们有空格。我想删除它,我的输出将是:

1,10,20,paris   
2,20,50,canada
3,10,23,london

我怎样才能通过python做到这一点?

【问题讨论】:

    标签: python csv


    【解决方案1】:

    这种更快的方法是使用文本编辑器:)

    如果你使用 vim

    %s/ //g
    

    %s - 应用于整个文件选择

    // - 替换的字母

    // - 替代

    g - 全局

    或简单地在任何编辑器中使用查找和替换

    在 python 中假设 file.csv 是你的文件

    with open('file.csv','r') as f:
        content = f.readlines()
        cleaned = ''
        for line in content:
            if line != '\n':
                cleaned += line
        print(cleaned.replace(" ",""))
    

    【讨论】:

      【解决方案2】:

      类似:

      with open(filename, 'r') as f:
          reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
          return [[x.strip() for x in row] for row in reader]
      

      我从这里得到了这个答案:Strip white spaces from CSV file

      【讨论】:

      • 它有一个错误:SyntaxError: 'return' outside function
      【解决方案3】:
      1. 你可以试试这个代码
      import csv
      
      aList=[]
      with open(self.filename, 'r') as f:
          reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
          return [[x.strip() for x in row] for row in reader]
      
      1. 或者您可以使用 Pandas 读取 CSV(或 Excel 文件)并使用此自定义函数对其进行修剪,如下所示
      #Definition for strippping whitespace
      def trim(dataset):
          trim = lambda x: x.strip() if type(x) is str else x
          return dataset.applymap(trim)
      

      然后您现在可以将修剪(CSV/Excel)应用到您的代码中(作为循环的一部分等)

      dataset = trim(pd.read_csv(dataset))
      dataset = trim(pd.read_excel(dataset))
      

      【讨论】:

      • 我尝试了第一个代码,但出现错误:SyntaxError: 'return' outside function
      【解决方案4】:

      我找到了答案:

      text = open("file.csv", "r", encoding="utf8")
              text = ''.join([i for i in text]) \
                  .replace("  ", "")
              x = open("file1" + i + ".csv", "w", encoding="utf8")
              x.writelines(text)
              x.close()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-17
        • 2013-01-04
        • 1970-01-01
        • 2020-06-19
        • 1970-01-01
        • 2016-05-11
        • 1970-01-01
        相关资源
        最近更新 更多