Python csv.DictWriter方法代码示例

本文整理汇总了Python中csv.DictWriter方法的典型用法代码示例。如果您正苦于以下问题:Python csv.DictWriter方法的具体用法?Python csv.DictWriter怎么用?Python csv.DictWriter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块csv的用法示例。

在下文中一共展示了csv.DictWriter方法的29个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: write_bars_to_file

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def write_bars_to_file(bars, filename, tz):
    """Creates CSV file from list of Bar instances"""
    date_format_str = "%Y%m%d %H%M%S"
    rows = [{'DateTime':  bar.datetime.astimezone(tz).strftime(date_format_str),
             'Open':	  bar.open,
             'High':	  bar.high,
             'Low':	      bar.low,
             'Close':	  bar.close,
             'Volume':	  bar.volume,
             } for bar in bars]
    if os.path.exists(filename):
        raise Exception("File already exists!")
    fd = os.popen("gzip > %s" % filename, 'w') if filename.endswith('.gz') else open(filename, 'w')
    with fd:
        csv_writer = csv.DictWriter(fd, ['DateTime', 'Open', 'High', 'Low', 'Close', 'Volume'])
        csv_writer.writeheader()
        csv_writer.writerows(rows) 
开发者ID:tibkiss,项目名称:iqfeed,代码行数:23,代码来源:tools.py


示例2: log

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def log(self, id: str, filename: str, row: Dict):
        """Write a to a CSV file.
        Parameters
        ----------
        id : str
            The ID of the function being tapped. This is used to generate a directory for the log file.
        filename : str
            The name of the CSV file.
        row : dict
            A dictionary that will be written as a row in the CSV. The keys should be in the
            CsvTap's list of ``column_names``.
        """
        path = self.path(id, filename)
        is_new = not os.path.exists(path)
        if is_new:
            os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "a") as f:
            writer = csv.DictWriter(f, fieldnames=self.column_names)
            if is_new:
                writer.writeheader()
            writer.writerow(row) 
开发者ID:erp12,项目名称:pyshgp,代码行数:25,代码来源:tap.py


示例3: write_csv

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def write_csv(output_filename, dict_list, delimiter, verbose=False):
    """Write a CSV file
    """
    if not dict_list:
        if verbose:
            print('Not writing %s; no lines to write' % output_filename)
        return
    dialect = csv.excel
    dialect.delimiter = delimiter
    with open(output_filename, 'w') as f:
        dict_writer = csv.DictWriter(f, fieldnames=dict_list[0].keys(),
                                     dialect=dialect)
        dict_writer.writeheader()
        dict_writer.writerows(dict_list)
    if verbose:
        print 'Wrote %s' % output_filename 
开发者ID:aimuch,项目名称:iAI,代码行数:21,代码来源:parse_log.py


示例4: analyseLocation

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def analyseLocation(friends):
    freqs = {}
    headers = ['NickName','Province','City']
    with open('location.csv','w',encoding='utf-8',newline='',) as csvFile:
        writer = csv.DictWriter(csvFile, headers)
        writer.writeheader()
        for friend in friends[1:]:
            row = {}
            row['NickName'] = friend['NickName']
            row['Province'] = friend['Province']
            row['City'] = friend['City']
            if(friend['Province']!=None):
                if(friend['Province'] not in freqs):
                   freqs[friend['Province']] = 1
                else:
                   freqs[friend['Province']] = 1
            writer.writerow(row)
    for (k,v) in freqs:
        print("{0}:{1}".format(k,v)) 
开发者ID:qinyuanpei,项目名称:wechat-analyse,代码行数:22,代码来源:main.py


示例5: __init__

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def __init__(self, filepath='./', filename='results{}.csv', data=None, local_rank=0):
        self.local_rank = local_rank
        self.log_path = filepath
        self.log_name = filename.format(self.local_rank)
        self.csv_path = os.path.join(self.log_path, self.log_name)
        self.fieldsnames = ['epoch', 'val_error1', 'val_error5', 'val_loss', 'train_error1', 'train_error5',
                            'train_loss']
        self.data = {}
        for field in self.fieldsnames:
            self.data[field] = []
        with open(self.csv_path, 'w') as f:
            writer = csv.DictWriter(f, fieldnames=self.fieldsnames)
            writer.writeheader()
        if data is not None:
            for d in data:
                d_num = {}
                for key in d:
                    d_num[key] = float(d[key]) if key != 'epoch' else int(d[key])
                self.write(d_num) 
开发者ID:Randl,项目名称:MobileNetV3-pytorch,代码行数:23,代码来源:logger.py


示例6: write

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def write(self, ordered_dict):
        '''
        write an entry
        :param ordered_dict: something like {'name':'exp1', 'acc':90.5, 'epoch':50}
        :return:
        '''
        if os.path.exists(self.filename) == False:
            headers = list(ordered_dict.keys())
            prev_rec = None
        else:
            with open(self.filename) as f:
                reader = csv.DictReader(f)
                headers = reader.fieldnames
                prev_rec = [row for row in reader]
            headers = self.merge_headers(headers, list(ordered_dict.keys()))
        with open(self.filename, 'w', newline='') as f:
            writer = csv.DictWriter(f, headers)
            writer.writeheader()
            if not prev_rec == None:
                writer.writerows(prev_rec)
            writer.writerow(ordered_dict) 
开发者ID:ChrisWu1997,项目名称:2D-Motion-Retargeting,代码行数:24,代码来源:utils.py


示例7: save_csv

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def save_csv(self):
        self.read_results()
        l_0 = self.dict_results_0['lists']['log_likelihood_time']
        l_1 = self.dict_results_1['lists']['log_likelihood_time']
        names_field = ['m0', 'm1']
        with open('./sample_results.csv', 'w') as f:
            writer_csv = csv.DictWriter(
                f, fieldnames = names_field
            )
            writer_csv.writeheader()
            for i_0, i_1 in zip(l_0, l_1):
                dict_temp = {
                    'm0': round(i_0, 4),
                    'm1': round(i_1, 4)
                }
                #print dict_temp
                writer_csv.writerow(
                    dict_temp
                )
        print "done ! "
    #
    # 
开发者ID:HMEIatJHU,项目名称:neurawkes,代码行数:24,代码来源:testers.py


示例8: save_cards_to_csv

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def save_cards_to_csv(self, csv_file,
                          front_column='front',
                          back_column='back'):
        """Save the word pairs from the deck's cards to a CSV file.
        Args:
            csv_file: The file buffer to store the CSV data in.
            front_column (str): Optional name for the 'front' column.
            back_column (str): Optional name for the 'back' column.
        Example:
            >>> with open(csv_path, 'w') as csv_file:
            >>>     deck.save_cards_to_csv(csv_file)
        """
        csv_writer = csv.DictWriter(csv_file,
                                    fieldnames=[front_column, back_column])
        # Add header row first.
        csv_writer.writeheader()
        # Then add all cards as rows.
        for card in self.cards:
            front_word = card.front.concepts[0].fact.text
            back_word = card.back.concepts[0].fact.text
            csv_writer.writerow({front_column: front_word,
                                 back_column: back_word}) 
开发者ID:floscha,项目名称:tinycards-python-api,代码行数:27,代码来源:deck.py


示例9: build_csv

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def build_csv(entries):
    """
    Creates a CSV string from a list of dict objects.
    The dictionary keys of the first item in the list are used as the header
    row for the built CSV. All item's keys are supposed to be identical.
    """
    if entries:
        header = entries[0].keys()
    else:
        return ''
    memfile = StringIO()
    writer = csv.DictWriter(memfile, header, lineterminator=os.linesep)
    writer.writeheader()
    writer.writerows(entries)
    output = memfile.getvalue()
    memfile.close()
    return output 
开发者ID:TailorDev,项目名称:Watson,代码行数:20,代码来源:utils.py


示例10: process_market_book

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def process_market_book(self, live_market, market_book):
        with open(self.file_directory, "a") as f:
            writer = csv.DictWriter(f, fieldnames=HEADERS)
            for runner in market_book.runners:
                writer.writerow(
                    {
                        "market_id": market_book.market_id,
                        "publish_time": market_book.publish_time,
                        "status": market_book.status,
                        "inplay": market_book.inplay,
                        "selection_id": runner.selection_id,
                        "last_price_traded": runner.last_price_traded,
                        "back": get_price(runner.ex.available_to_back, 0),
                        "lay": get_price(runner.ex.available_to_lay, 0),
                    }
                ) 
开发者ID:liampauling,项目名称:flumine,代码行数:18,代码来源:pricerecorder.py


示例11: generate_modified_file

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def generate_modified_file(src, dst, sample, corrupt):
    """원본 파일을 샘플링하고 결측치 넣은 새 파일 생성"""
    # 랜덤 시드 고정. 매번 동일한 결과가 보장되도록.
    random.seed(0)
    with open(src, 'r') as fr:
        with open(dst, 'w') as fw:
            csvr = csv.DictReader(fr)
            csvw = csv.DictWriter(fw, csvr.fieldnames)
            csvw.writeheader()
            rows = csvr
            # 샘플링
            if sample:
                rows = (row for row in rows if random.random() <= SAMPLE_RATE)
            # 결측치 추가
            if corrupt:
                rows = (corrupt_row(row) for row in rows)
            csvw.writerows(rows) 
开发者ID:akngs,项目名称:petitions,代码行数:24,代码来源:petition.py


示例12: dump_meter

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def dump_meter(self, name, obj):
        # we already know its kind
        kind = obj.pop('kind')
        # add the current time
        obj['time'] = time.time()
        file_name, new = self.file_name(name, kind)
        with open(file_name, "a" if py3comp.PY3 else "ab") as of:
            writer = csv.DictWriter(of, self.meter_header)
            # if the file is new, write the header once
            if new:
                writer.writerow(dict(zip(self.meter_header, self.meter_header)))
            writer.writerow(obj)
        return file_name 
开发者ID:avalente,项目名称:appmetrics,代码行数:22,代码来源:reporter.py


示例13: readInputData

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def readInputData(self,fname=None):
        if fname is None:
            fname = '%s-input.csv' % (self.filename)
        if os.path.isfile(fname):
            self.data = self.readDataFile(fname)
        else:
            raw = self.readDataFile('%s-raw.csv' % (self.filename))
            self.processData(raw)
            fields = sorted(next(iter(self.data.values())).keys())
            for row in self.data.values():
                assert set(row.keys()) == set(fields)
            with open(fname,'w') as csvfile:
                writer = csv.DictWriter(csvfile,fields,extrasaction='ignore')
                writer.writeheader()
                for ID,record in sorted(self.data.items()):
                    writer.writerow(record) 
开发者ID:pynadath,项目名称:psychsim,代码行数:18,代码来源:modeling.py


示例14: main

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def main():
    translations = extract_translations(file_path)
    cds = extract_cds(file_path)
    for i, translation in enumerate(translations):
        print("Getting translation " + str(i + 1) + "/"
              + str(len(translations)) + "...")
        url = get_translation_url(translation)
        result = get_values(url)
        for index_row, row in enumerate(result):
            row["translation_number"] = i + 1
            row["cds"] = cds[i]
            if i == 0 and index_row == 0:
                with open(file_path_without_ext + '.csv', 'w') as f:
                    w = csv.DictWriter(f, row.keys())
                    w.writeheader()
            with open(file_path_without_ext + '.csv', 'a') as f:
                w = csv.DictWriter(f, row.keys())
                w.writerow(row) 
开发者ID:phageParser,项目名称:phageParser,代码行数:23,代码来源:pfam_db.py


示例15: write

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def write(self, fileName, writeHeader=True):
		isDict = type(self.dic[0]) == dict
		with open(fileName, 'w') as fs:
			headings = None
			if isDict:
				headings = self.dic[0].keys()
			else:
				headings = self.dic[0].attribs()
			w = csv.DictWriter(fs, headings)
			if writeHeader:
				w.writerow( dict((fn,fn) for fn in headings))
			if isDict:
				for row in self.dic:
					w.writerow(row)
			else:
				for row in self.dic:
					w.writerow(row.__dict__) 
开发者ID:samarsault,项目名称:CSV-Mapper,代码行数:21,代码来源:csv_parser.py


示例16: save_predictions

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def save_predictions(pred, file):
    """
    Save predictions to CSV file
    Args:
        pred: numpy array, of numeric predictions
        file: str, filename + extension
    """
    with open(file, 'w') as csvfile:
        fieldnames = ['Stance']
        writer = DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for instance in pred:
            writer.writerow({'Stance': label_ref_rev[instance]}) 
开发者ID:GauravBh1010tt,项目名称:DeepLearn,代码行数:18,代码来源:util.py


示例17: json_to_csv

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def json_to_csv(json, **writer_opts):
    # CSVs with one item are treated as lists of 1 element
    if not isinstance(json, list):
        json = [json]
    # Calculate the fieldnames
    fields = set()
    for row in json:
        flattened = flatten_dicts(row, delim="\t")
        # flattened = flatten_preserve_lists(row, max_depth=2)
        fields.update(flattened.keys())
    # Write the CSV
    with StringIO() as fp:
        writer = csv.DictWriter(fp, fieldnames=fields, **writer_opts)
        writer.writeheader()
        for row in json:
            flattened = flatten_dicts(row, delim="\t")
            writer.writerow(flattened)
        return fp.getvalue() 
开发者ID:ewels,项目名称:MegaQC,代码行数:23,代码来源:content.py


示例18: write_reservation_usage

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def write_reservation_usage(f, reservation_usage, header=True):
    writer = csv.DictWriter(f, fieldnames=[
        'instance_type',
        'availability_zone',
        'tenancy',
        'product',
        'cost_hourly',
        'cost_upfront',
        'count',
        'count_used',
    ])
    if header:
        writer.writeheader()
    for ru in reservation_usage:
        writer.writerow({
            'instance_type': ru.instance_reservation.type.size,
            'availability_zone': ru.instance_reservation.type.availability_zone,
            'tenancy': ru.instance_reservation.type.tenancy,
            'product': ru.instance_reservation.type.product,
            'cost_hourly': ru.instance_reservation.cost_hourly,
            'cost_upfront': ru.instance_reservation.cost_upfront,
            'count': ru.count,
            'count_used': ru.count_used,
        }) 
开发者ID:trackit,项目名称:aws-cost-report,代码行数:26,代码来源:get_ec2_data.py


示例19: report

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def report(self, column_names, columns, cfg=None, **kwargs):
        formated_columns = []
        for column in columns:
            formated_column = []
            for value in column:
                if isinstance(value, int):
                    formated_column.append(value)
                    #formated_column.append("{:,}".format(value))
                elif isinstance(value, float):
                    formated_column.append("%.4f" % value)
                else:
                    formated_column.append(value)
            formated_columns.append(formated_column)
        writer = csv.DictWriter(self.fd, fieldnames=column_names)
        writer.writeheader()
        for i in range(len(formated_columns[0])):
            row = dict([(column_names[j], formated_columns[j][i])
                for j in range(len(formated_columns))])
            writer.writerow(row)
        self.report_config(cfg) 
开发者ID:actionml,项目名称:ur-analysis-tools,代码行数:25,代码来源:report.py


示例20: save_repo_request_rows

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def save_repo_request_rows(rows):
    with open('out.csv','wb') as f:
        w = csv.DictWriter(f, fieldnames=RepoRequest.list_fieldnames(), encoding='utf-8-sig')
        for row in rows[1:]:  # skip header row
            my_repo_request = RepoRequest()
            my_repo_request.set_id_seed(row[0])
            column_num = 0
            for fieldname in RepoRequest.list_fieldnames():
                if fieldname != "id":
                    setattr(my_repo_request, fieldname, row[column_num])
                    column_num += 1
            w.writerow(my_repo_request.to_dict())
            print u"adding repo request {}".format(my_repo_request)
            db.session.merge(my_repo_request)
        safe_commit(db) 
开发者ID:ourresearch,项目名称:oadoi,代码行数:22,代码来源:put_repo_requests_in_db.py


示例21: test_write_fields_not_in_fieldnames

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def test_write_fields_not_in_fieldnames(self):
        fd, name = tempfile.mkstemp()
        fileobj = os.fdopen(fd, "w+b")
        try:
            writer = csv.DictWriter(fileobj, fieldnames = ["f1", "f2", "f3"])
            # Of special note is the non-string key (issue 19449)
            with self.assertRaises(ValueError) as cx:
                writer.writerow({"f4": 10, "f2": "spam", 1: "abc"})
            exception = str(cx.exception)
            self.assertIn("fieldnames", exception)
            self.assertIn("'f4'", exception)
            self.assertNotIn("'f2'", exception)
            self.assertIn("1", exception)
        finally:
            fileobj.close()
            os.unlink(name) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:18,代码来源:test_csv.py


示例22: __init__

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def __init__(self, env, filename, allow_early_resets=False, reset_keywords=(), info_keywords=()):
        Wrapper.__init__(self, env=env)
        self.tstart = time.time()
        if filename is None:
            self.f = None
            self.logger = None
        else:
            if not filename.endswith(Monitor.EXT):
                if osp.isdir(filename):
                    filename = osp.join(filename, Monitor.EXT)
                else:
                    filename = filename + "." + Monitor.EXT
            self.f = open(filename, "wt")
            self.f.write('#%s\n'%json.dumps({"t_start": self.tstart, 'env_id' : env.spec and env.spec.id}))
            self.logger = csv.DictWriter(self.f, fieldnames=('r', 'l', 't')+reset_keywords+info_keywords)
            self.logger.writeheader()
            self.f.flush()
        self.reset_keywords = reset_keywords
        self.info_keywords = info_keywords
        self.allow_early_resets = allow_early_resets
        self.rewards = None
        self.needs_reset = True
        self.episode_rewards = []
        self.episode_lengths = []
        self.episode_times = []
        self.total_steps = 0
        self.current_reset_info = {} # extra info about the current episode, that was passed in during reset() 
开发者ID:Hwhitetooth,项目名称:lirpg,代码行数:30,代码来源:monitor.py


示例23: write_metadata

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def write_metadata(self, fpath):
    """Writes metadata file for Tensorboard word embedding visualizer as described here:
      https://www.tensorflow.org/get_started/embedding_viz
    Args:
      fpath: place to write the metadata file
    """
    print("Writing word embedding metadata file to %s..." % (fpath))
    with open(fpath, "w") as f:
      fieldnames = ['word']
      writer = csv.DictWriter(f, delimiter="\t", fieldnames=fieldnames)
      for i in range(self.size()):
        writer.writerow({"word": self._id_to_word[i]}) 
开发者ID:yaserkl,项目名称:TransferRL,代码行数:15,代码来源:data.py


示例24: update_canons_view

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def update_canons_view(self, request, document_set_id):
      """Update canons for the document set"""
      def _encode_dict_for_csv(d):
          rv = {}
          for k,v in d.items():
              k = k.encode('utf8') if type(k) == unicode else k
              if type(v) == datetime:
                  rv[k] = v.strftime('%Y-%m-%d %H:%M')
              elif type(v) == unicode:
                  rv[k] = v.encode('utf8')
              elif type(v) == bool:
                  rv[k] = 'true' if v else 'false'
              else:
                  rv[k] = v
          return rv
      response = django.http.HttpResponse(mimetype="text/csv")
      writer = csv.DictWriter(response, fieldnames=['entry_id', 'entry_value', 'entry_canonical_value'],extrasaction='ignore')
      writer.writeheader()
      for entry in models.DocumentSetFieldEntry.objects.all():
        if models.DocumentSetFormField.objects.get(pk=entry.field_id).autocomplete:
          try:
            entry.canonical_label = entry.get_canonical_value()
            entry.save()
            mensaje = entry.canonical_label.value
          except Exception, e:
            mensaje = "Failed %s" % e
          writer.writerow(_encode_dict_for_csv({'entry_id': entry.id, 'entry_value': entry.value, 'entry_canonical_value': mensaje})) 
开发者ID:crowdata,项目名称:crowdata,代码行数:34,代码来源:admin.py


示例25: __init__

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def __init__(self):
        # Create the olympe.Drone object from its IP address
        self.drone = olympe.Drone(DRONE_IP)
        self.tempd = tempfile.mkdtemp(prefix="olympe_streaming_test_")
        print("Olympe streaming example output dir: {}".format(self.tempd))
        self.h264_frame_stats = []
        self.h264_stats_file = open(
            os.path.join(self.tempd, 'h264_stats.csv'), 'w+')
        self.h264_stats_writer = csv.DictWriter(
            self.h264_stats_file, ['fps', 'bitrate'])
        self.h264_stats_writer.writeheader()
        self.frame_queue = queue.Queue()
        self.flush_queue_lock = threading.Lock()
        super().__init__()
        super().start() 
开发者ID:Parrot-Developers,项目名称:olympe,代码行数:17,代码来源:streaming.py


示例26: write_file

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def write_file(output_directory, table_name, schema, values):
    file_name = os.path.join(output_directory, '%s.csv' % (table_name,))
    with open(file_name, 'w') as write_file:
        writer = csv.DictWriter(write_file, fieldnames=schema)
        writer.writeheader()
        for value in values:
            writer.writerow(dict(zip(schema, value))) 
开发者ID:mwildehahn,项目名称:mysql-dump-to-csv,代码行数:9,代码来源:mysql_dump_to_csv.py


示例27: write

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def write(self, row, filename, method='a'):
        '''
        Writes to file, default appends. If filename does not exist, creates
        file with self.columns as headers then writes row. If called with
        method = 'w', will overwrite existing file with row.
        '''
        if not os.path.exists(filename) and method is 'a':
            self.write(row, filename, 'w')
        with open(filename, method) as f:
            writer = csv.DictWriter(f, fieldnames = self.columns)
            if method == 'w':
                writer.writeheader()
            writer.writerow(row) 
开发者ID:aldengolab,项目名称:fake-news-detection,代码行数:15,代码来源:csv_transform.py


示例28: write

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def write(self, data):
        for k in self.data:
            self.data[k].append(data[k])
        with open(self.csv_path, 'a') as f:
            writer = csv.DictWriter(f, fieldnames=self.fieldsnames)
            writer.writerow(data) 
开发者ID:Randl,项目名称:MobileNetV3-pytorch,代码行数:8,代码来源:logger.py


示例29: save_csv

# 需要导入模块: import csv [as 别名]
# 或者: from csv import DictWriter [as 别名]
def save_csv(self, path_save):
        print "saving logs into a csv ... "
        assert(len(self.list_logs)>0 )
        path_save = os.path.abspath(path_save)
        #path_save = path_save + '/' + 'logs.csv'
        #
        names_field = []
        for dict_args in self.list_logs:
            for the_key in dict_args:
                if the_key not in names_field:
                    names_field.append(the_key)
        names_field.sort()
        #
        with open(path_save, 'w') as file_csv:
            writer_csv = csv.DictWriter(
                file_csv, fieldnames = names_field
            )
            writer_csv.writeheader()
            for dict_args in self.list_logs:
                writer_csv.writerow(
                    dict_args
                )
            #
        print "done ! "
        #
    #
#
# 
开发者ID:HMEIatJHU,项目名称:neurawkes,代码行数:30,代码来源:organizers.py



注:本文中的csv.DictWriter方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。