Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过重新排列列和行来重写csv文件_Python_Python 3.x_Csv - Fatal编程技术网

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

Python 通过重新排列列和行来重写csv文件,python,python-3.x,csv,Python,Python 3.x,Csv,我有一个csv文件(我们称之为input.csv),看起来像这样: 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 ID; Field; Sent; Points; 1; Text_1;"Hello world one"; 33 1; Text_2;"Hello

我有一个csv文件(我们称之为input.csv),看起来像这样:

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
 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),它可以像这样重新排列列:

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
 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
这似乎不像我想象的那么容易。我想知道是否有办法直接转录这个文件。提前谢谢

我在一些帮助下尝试了这个方法,但是我很难按照我说的顺序阅读和复制列和行

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

下面的代码不会提供您确切需要的内容,但我相信它将帮助您重新组织
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
上述程序将输出:

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

下面的代码不会提供您确切需要的内容,但我相信它将帮助您重新组织
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
上述程序将输出:

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

只需读取每一行并写出两行,其中包含适当的字段:

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还有其他引用选项。

只需读取每一行并写出两行相应的字段即可:

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还有其他引用选项。

您可以尝试以下方法:

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()]
您可以尝试以下方法:

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

到目前为止你试过写一些代码吗?我编辑了这个问题,复制了一段到目前为止我所掌握的不连贯的代码。谢谢。到目前为止你试过写一些代码吗?我编辑了这个问题,复制了一段到目前为止我所掌握的不连贯的代码。谢谢。谢谢你的回答。问题是我在处理大文件、大量数据。因此,我无法在writerows中逐行写入文本。例如,我的意思是,假设您有1000行。@pyring在问题中没有指定,但1000行并不多。如果你有大量的数据,你应该使用数据库而不是CSV文件。谢谢@Mark Tolonen。你的回答对我帮助很大。谢谢你的回答。问题是我在处理大文件、大量数据。因此,我无法在writerows中逐行写入文本。例如,我的意思是,假设您有1000行。@pyring在问题中没有指定,但1000行并不多。如果你有大量的数据,你应该使用数据库而不是CSV文件。谢谢@Mark Tolonen。你的回答对我帮助很大。