【问题标题】:CSV Modification PythonCSV 修改 Python
【发布时间】:2018-02-28 17:09:52
【问题描述】:

我在处理 CSV 文件时遇到困难。我需要一个 pythonic 解决方案,它可以读取带有如下行的 CSV:

并生成一个输出(最好使用相同的 CSV 名称)来产生这个:

(Row1Row2Row3等所有标题信息都应删除,值类型行指定Number 也应该删除)

某种 pandas/python 解决方案是否可行?我一直在尝试,但无济于事。

任何指导也会有很大帮助,因为我是新手。

【问题讨论】:

    标签: python pandas csv export-to-csv


    【解决方案1】:

    我认为这个问题可以这样解决。

    f = open("new.csv","w")
    for line in open("sample.csv").readlines():
        temp = line.split(",").strip()
        if len(temp) < 4 : pass
        else :
            if temp[0] == "Number": pass
            else : f.write(line)
    f.close()
    

    【讨论】:

      【解决方案2】:

      这应该可以解决问题,使用 xlrd 和 xlwt:

      import xlrd, xlwt, os
      
      book = xlrd.open_workbook('Path to input file to read')
      sheet = book.sheet_by_index(0)
      nrows = sheet.nrows
      ncols = sheet.ncols
      
      outputs = []
      for i in range(nrows):
          if str(sheet.cell(i,0).value).startswith('Row') or str(sheet.cell(i,0).value).startswith('Number'):
              continue
          else:
              outputs.append([sheet.cell(i,j).value for j in range(ncols)])
      
      os.chdir('Path to save output file')
      out = xlwt.Workbook()
      sheet1 = out.add_sheet('Output')
      for row, i in enumerate(outputs):
          for col, j in enumerate(i):
              sheet1.write(row, col, str(j))
      out.save('out.xls')
      

      【讨论】:

        【解决方案3】:
        import csv
        with open('old.csv', newline='') as fr, open('new.csv', 'w', newline='') as fw:
            reader, writer = csv.reader(fr), csv.writer(fw)
            for row in reader:
               # skip rows until 'Value1'
               if row[0] == 'Value1':
                   writer.writerow(row)
                   break
            # skip type descriptions
            next(reader) 
            # write the rest of rows
            writer.writerows(list(reader)) 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-30
          • 2017-04-27
          • 1970-01-01
          • 2015-05-31
          • 1970-01-01
          相关资源
          最近更新 更多