CSV修改Python

时间:2018-02-28 17:09:52

标签: python pandas csv export-to-csv

我在处理CSV文件时遇到了困难。我需要一个pythonic解决方案,用以下行读取CSV: Excel Sheet

并生成一个输出(最好使用相同的CSV名称)来生成: enter image description here

(应删除所有标题信息,例如 Row1 Row2 Row3 ,并指定值类型行数字也应该删除)

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

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

3 个答案:

答案 0 :(得分: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()

答案 1 :(得分:1)

这应该可以解决问题,使用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')

答案 2 :(得分:1)

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