当前位置: 首页>>代码示例>>Python>>正文


Python csv.DictWriter方法代码示例

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


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


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