CSV修改Python

问题描述 投票:0回答:3

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

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

(应删除所有标题信息,如Row1,Row2,Row3,并且还应删除指定Number的值类型行)

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

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

python pandas csv export-to-csv
3个回答
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
投票

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

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)) 
© www.soinside.com 2019 - 2024. All rights reserved.