0

いくつかのサンプルデータ:

title1|title2|title3|title4|merge
test|data|here|and
test|data|343|AND
",3|data|343|and

これをコーディングする私の試み:

import csv
import StringIO

storedoutput = StringIO.StringIO()
fields = ('title1', 'title2', 'title3', 'title4', 'merge')
with open('file.csv', 'rb') as input_csv:
    reader = csv.DictReader(input_csv, fields, delimiter='|')
    for counter, row in enumerate(reader):
        counter += 1
        #print row
        if counter != 1:
            for field in fields:
                if field == "merge":
                    row['merge'] = ("%s%s%s" % (row["title1"], row["title3"], row["title4"]))
                    print row
                    storedoutput.writelines(','.join(map(str, row)) + '\n')

contents = storedoutput.getvalue()
storedoutput.close()

print "".join(contents)

with open('file.csv', 'rb') as input_csv:
    input_csv = input_csv.read().strip()

output_csv = []
output_csv.append(contents.strip())

if "".join(output_csv) != input_csv:
    with open('file.csv', 'wb') as new_csv:
        new_csv.write("".join(output_csv))

出力は

title1|title2|title3|title4|merge
test|data|here|and|testhereand
test|data|343|AND|test343AND
",3|data|343|and|",3343and

このコードを実行する際の参考のために、最初の出力では、出力 csv に表示されるように行が出力されます。ただし、2 番目の印刷では、タイトル行が x 回印刷されます。ここで、x は行数です。

入力、修正、または作業コードをいただければ幸いです。

4

3 に答える 3

2

最後の行の二重引用符は間違いなく csv.DictReader() を台無しにしています。これは機能します:

new_lines = []
with open('file.csv', 'rb') as f:
    # skip the first line
    new_lines.append(f.next().strip())
    for line in f:
        # the newline and split the fields
        line = line.strip().split('|')
        # exctract the field data you want
        title1, title3, title4 = line[0], line[2], line[3]
        # turn the field data into a string and append in to the rest
        line.append(''.join([title1, title3, title4]))
        # save the new line for later
        new_lines.append('|'.join(line))

with open('file.csv', 'w') as f:
    # make one long string and write it to the new file
    f.write('\n'.join(new_lines))
于 2013-10-19T02:31:38.190 に答える
0
import csv
import StringIO

stored_output = StringIO.StringIO()

with open('file.csv', 'rb') as input_csv:
    reader = csv.DictReader(input_csv, delimiter='|', quoting=csv.QUOTE_NONE)
    writer = csv.DictWriter(stored_output, reader.fieldnames, delimiter="|",quoting=csv.QUOTE_NONE, quotechar=None)

    merge_cols = "title1", "title3", "title4"

    writer.writeheader()

    for row in reader:
        row["merge"] = ''.join(row[col] for col in merge_cols)
        writer.writerow(row)

    contents = stored_output.getvalue()
    stored_output.close()
    print contents

with open('file.csv', 'rb') as input_csv:
    input_csv = input_csv.read().strip()

if input_csv != contents.strip():
    with open('file.csv', 'wb') as new_csv:
        new_csv.write("".join(contents))
于 2013-10-19T02:46:53.010 に答える