1

新しいファイルに書き込む代わりに、次のコードを同じファイルに書き込むように変換するにはどうすればよいですか?

import csv
import itertools
from operator import itemgetter

def filter_data(data):
    for classname, group in itertools.groupby(data, itemgetter(2)):
        filtered_group = [line for line in group]
        new_count = len(filtered_group)
        for line in filtered_group:
            if line[5] == "Count":
                line[5] = "Counter"
            else:
                line[5] = new_count
            yield line

with open('main.csv', 'rb') as f_in, open('main1.csv', 'wb') as f_out:
    reader = csv.reader(f_in)
    writer = csv.writer(f_out)
    writer.writerows(filter_data(reader))

stringio が機能していない場合の私の注意点...

import csv
import itertools
from operator import itemgetter
import StringIO

def filter_data(data):
    for classname, group in itertools.groupby(data, itemgetter(2)):
        filtered_group = [line for line in group]
        new_count = len(filtered_group)
        for line in filtered_group:
            if line[5] == "Count":
                line[5] = "Counter"
            else:
                line[5] = new_count
            yield line

output = StringIO.StringIO()

with open('../main.csv', 'rb') as f_in:
    reader = csv.reader(f_in)
    output.writelines(filter_data(reader))

contents = output.getvalue()
output.close()

with open('../main_test.csv', 'wb') as f_out: 
    f_out.writelines(contents)
4

1 に答える 1

1

次のことを試してください。

コード

import csv
import itertools
from operator import itemgetter
import StringIO

def filter_data(data):
    for classname, group in itertools.groupby(data, itemgetter(2)):
        filtered_group = [line for line in group]
        new_count = len(filtered_group)
        for line in filtered_group:
            if line[5] == "Count":
                line[5] = "Counter"
            else:
                line[5] = new_count
            yield ','.join(map(str, line)) + '\n'

output = StringIO.StringIO()

with open('../main.csv', 'rb') as f_in:
    reader = csv.reader(f_in)
    output.writelines(filter_data(reader))

contents = output.getvalue()
output.close()

with open('../main.csv', 'wb') as f_out: 
    f_out.writelines(contents)

これはうまくいくはずです:)

于 2013-10-12T00:04:09.000 に答える