通过重新排列列和行来重写csv文件

时间:2017-11-16 22:13:18

标签: python python-3.x csv

我有一个csv文件(让我们称之为input.csv),如下所示:

 ID; Field; Sent; Points;
 1; Text_1;"Hello world one"; 33
 1; Text_2;"Hello world two"; 90
 2; Text_1;"Goodbye world one"; 44
 2; Text_2;"Goodbye world two"; 100

我想创建另一个csv文件(让我们称之为output.csv)重新排列这样的列:

with open("results.csv", "r") as text:
    reader = csv.DictReader(text, delimiter=";")

rows = [l.split(";") for l in text.split("\n")]
del filas[0] 

newlist = list()
for l in filas:
  newlist.append([l[0], 'Texto_1', l[2]])
  newlist.append([l[0], 'Texto_2', l[4]])

它似乎并不像我想象的那样容易。我想知道是否有办法直接转录该文件。提前谢谢。

我已经尝试了一些帮助,但是我按照我说的顺序阅读和复制列和行有困难。

pos_*

3 个答案:

答案 0 :(得分:1)

只需读取每一行,并用适当的字段写出两行:

import csv

with open('input.csv','r',newline='') as infile:
    with open('output.csv','w',newline='') as outfile:
        r = csv.reader(infile,delimiter=';')
        w = csv.writer(outfile,delimiter=';')
        next(r) # skip the original header
        w.writerow('ID Field Sent Points'.split())
        for id,t1,p1,t2,p2 in r:
            w.writerows([[id,'Text_1',t1,p1],
                         [id,'Text_2',t2,p2]])

输出:

ID;Field;Sent;Points
1;Text_1;Hello world one;33
1;Text_2;Hello world two;90
2;Text_1;Goodbye world one;44
2;Text_2;Goodbye world two;100

注意:除非字段包含分隔符,否则.csv模块不需要引号。如果您需要,csv.writer可以引用其他选项。

答案 1 :(得分:0)

以下代码不会为您提供您正在寻找的内容,但我相信它可以帮助您重新组织MSBuild文件中的列。

csv

对于以下输入:

import csv

with open('input.csv', 'r') as infile, open('output.csv', 'w') as outfile:
    # output dict needs a list for new column ordering
    fieldnames = ['ID', 'Text_1', 'Text_2', 'Points_1', 'Points_2']
    writer = csv.DictWriter(outfile, fieldnames=fieldnames)
    # reorder the header first
    writer.writeheader()
    for row in csv.DictReader(infile):
        # writes the reordered rows to the new file
        writer.writerow(row)

上述程序将输出:

ID, Text_1, Points_1, Text_2, Points_2
1, "Hello world one", 33, "Hello world two", 90
2, "Goodbye world one", 44, "Goodbye world two",100

答案 2 :(得分:0)

你可以试试这个:

def get_data()
   with open('filename.csv') as f:
      data = [i.strip('\n').split('; ') for i in f]
      header = data[0]
      for i, a in enumerate(data):
          yield [data[0], header[1], data[1], data[2]]
          yield [data[0], header[3], data[3], data[4]]

final_data = ['; '.join(i) for i in get_data()]