CSV 修改 Python

CSV Modification Python

我在处理 CSV 文件时遇到困难。我需要一个 pythonic 解决方案来读取包含以下行的 CSV:

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

(所有 header 信息,例如 Row1Row2Row3应该删除并且指定 Number 的值类型行也应该删除)

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

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

我觉得这个问题可以这样解决

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

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