當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。