本文整理汇总了Python中csv.writer方法的典型用法代码示例。如果您正苦于以下问题:Python csv.writer方法的具体用法?Python csv.writer怎么用?Python csv.writer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类csv
的用法示例。
在下文中一共展示了csv.writer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save_id_to_path_mapping
# 需要导入模块: import csv [as 别名]
# 或者: from csv import writer [as 别名]
def save_id_to_path_mapping(self):
"""Saves mapping from submission IDs to original filenames.
This mapping is saved as CSV file into target directory.
"""
if not self.id_to_path_mapping:
return
with open(self.local_id_to_path_mapping_file, 'w') as f:
writer = csv.writer(f)
writer.writerow(['id', 'path'])
for k, v in sorted(iteritems(self.id_to_path_mapping)):
writer.writerow([k, v])
cmd = ['gsutil', 'cp', self.local_id_to_path_mapping_file,
os.path.join(self.target_dir, 'id_to_path_mapping.csv')]
if subprocess.call(cmd) != 0:
logging.error('Can\'t copy id_to_path_mapping.csv to target directory')
示例2: download_results
# 需要导入模块: import csv [as 别名]
# 或者: from csv import writer [as 别名]
def download_results(request):
import csv
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="orders.csv"'
writer = csv.writer(response)
header = [
'CODE',
'CUSTOMER',
'CREATED_AT',
'ASSIGNED_TO',
'CHECKED_IN',
'LOCATION'
]
writer.writerow(header)
for o in request.session['order_queryset']:
row = [o.code, o.customer, o.created_at,
o.user, o.checkin_location, o.location]
coded = [unicode(s).encode('utf-8') for s in row]
writer.writerow(coded)
return response
示例3: write
# 需要导入模块: import csv [as 别名]
# 或者: from csv import writer [as 别名]
def write(self, epoch, step, data):
if not self.ks:
return
# Make sure that keys have no underscores.
data = {k.replace('_', '-'):v for k, v in data.items()}
row = [epoch, step]
for k in self.ks:
if k in data:
row.append(_toscalar(data[k]))
self.prev[k] = data[k]
elif k in self.prev:
row.append(_toscalar(self.prev[k]))
else:
row.append(None)
self.writer.writerow(row)
示例4: _save_sorted_results
# 需要导入模块: import csv [as 别名]
# 或者: from csv import writer [as 别名]
def _save_sorted_results(self, run_stats, scores, image_count, filename):
"""Saves sorted (by score) results of the evaluation.
Args:
run_stats: dictionary with runtime statistics for submissions,
can be generated by WorkPiecesBase.compute_work_statistics
scores: dictionary mapping submission ids to scores
image_count: dictionary with number of images processed by submission
filename: output filename
"""
with open(filename, 'w') as f:
writer = csv.writer(f)
writer.writerow(['SubmissionID', 'ExternalTeamId', 'Score',
'MedianTime', 'ImageCount'])
get_second = lambda x: x[1]
for s_id, score in sorted(iteritems(scores),
key=get_second, reverse=True):
external_id = self.submissions.get_external_id(s_id)
stat = run_stats.get(
s_id, collections.defaultdict(lambda: float('NaN')))
writer.writerow([s_id, external_id, score,
stat['median_eval_time'],
image_count[s_id]])
示例5: generate_bi_graphemes_dictionary
# 需要导入模块: import csv [as 别名]
# 或者: from csv import writer [as 别名]
def generate_bi_graphemes_dictionary(label_list):
freqs = Counter()
for label in label_list:
label = label.split(' ')
for i in label:
for pair in split_every(2, i):
if len(pair) == 2:
freqs[pair] += 1
with open('resources/unicodemap_en_baidu_bi_graphemes.csv', 'w') as bigram_label:
bigramwriter = csv.writer(bigram_label, delimiter = ',')
baidu_labels = list('\' abcdefghijklmnopqrstuvwxyz')
for index, key in enumerate(baidu_labels):
bigramwriter.writerow((key, index+1))
for index, key in enumerate(freqs.keys()):
bigramwriter.writerow((key, index+len(baidu_labels)+1))
示例6: get_denominator_csv
# 需要导入模块: import csv [as 别名]
# 或者: from csv import writer [as 别名]
def get_denominator_csv(self):
output = io.StringIO()
writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(["year", "month", "officers out on service"])
values = sorted(self.denominator_values,
key=lambda x: (x.year, x.month))
for value in values:
row = [
value.year,
value.month,
value.officers_out_on_service
]
writer.writerow(row)
return output.getvalue()
示例7: execute
# 需要导入模块: import csv [as 别名]
# 或者: from csv import writer [as 别名]
def execute(self, parameters, messages):
"""The source code of the tool."""
in_drainage_line = parameters[0].valueAsText
out_csv_file = parameters[1].valueAsText
fields = ['NextDownID', 'HydroID']
list_all = []
'''The script line below makes sure that rows in the subset file are
arranged in descending order of NextDownID of stream segements'''
for row in sorted(arcpy.da.SearchCursor(in_drainage_line, fields), reverse=True):
list_all.append([row[1]])
with open(out_csv_file,'wb') as csvfile:
connectwriter = csv.writer(csvfile, dialect='excel')
for row_list in list_all:
out = row_list
connectwriter.writerow(out)
return
示例8: reset
# 需要导入模块: import csv [as 别名]
# 或者: from csv import writer [as 别名]
def reset(self):
import csv
kwargs = {"newline": "", "encoding": "utf-8"}
mode = "wt"
if self.complib == "gzip":
import gzip
self._fh = gzip.open(self.csvfile, mode, self.complevel, **kwargs)
elif self.complib in ("bz2", "bzip2"):
import bz2
self._fh = bz2.open(self.csvfile, mode, self.complevel, **kwargs)
elif self.complib is None:
self._fh = open(self.csvfile, mode, **kwargs)
else:
raise KeyError("Unexpected compression library: {}".format(self.complib))
self._writer = csv.writer(self._fh, **self.csv_kwargs)
# Write header data
row = ["Datetime"] + [name for name in self._node_names]
self._writer.writerow(row)
示例9: get_data
# 需要导入模块: import csv [as 别名]
# 或者: from csv import writer [as 别名]
def get_data():
filenames = [os.path.splitext(f)[0] for f in glob.glob("original/*.jpg")]
jpg_files = [s + ".jpg" for s in filenames]
txt_files = [s + ".txt" for s in filenames]
for file in txt_files:
boxes = []
with open(file, "r", encoding="utf-8", newline="") as lines:
for line in csv.reader(lines):
boxes.append([line[0], line[1], line[6], line[7]])
with open('mlt/label/' + file.split('/')[1], "w+") as labelFile:
wr = csv.writer(labelFile)
wr.writerows(boxes)
for jpg in jpg_files:
shutil.copy(jpg, 'mlt/image/')
示例10: process_txt
# 需要导入模块: import csv [as 别名]
# 或者: from csv import writer [as 别名]
def process_txt():
filenames = [os.path.splitext(f)[0] for f in glob.glob("test_result/*.txt")]
old_files = [s + ".txt" for s in filenames]
for old_file in old_files:
new = []
with open(old_file, "r") as old:
for line in csv.reader(old):
if not line:
continue
if not line[0]:
continue
if line[0][0] == ' ' or line[0][-1] == ' ':
line[0] = line[0].strip()
if ' ' in line[0]:
line = line[0].split(' ')
new.append(line)
with open('task2_result/' + old_file.split('/')[1], "w+") as newfile:
wr = csv.writer(newfile, delimiter = '\n')
new = [[s[0].upper()] for s in new]
wr.writerows(new)
示例11: for_task3
# 需要导入模块: import csv [as 别名]
# 或者: from csv import writer [as 别名]
def for_task3():
filenames = [os.path.splitext(f)[0] for f in glob.glob("boundingbox/*.txt")]
box_files = [s + ".txt" for s in filenames]
for boxfile in box_files:
box = []
with open(boxfile,'r') as boxes:
for line in csv.reader(boxes):
box.append([int(string, 10) for string in line[0:8]])
words = []
with open('test_result/'+ boxfile.split('/')[1], 'r') as prediction:
for line in csv.reader(prediction):
words.append(line)
words = [s if len(s)!=0 else [' '] for s in words]
new = []
for line in zip(box,words):
a,b = line
new.append(a+b)
with open('for_task3/'+ boxfile.split('/')[1], 'w+') as newfile:
csv_out = csv.writer(newfile)
for line in new:
csv_out.writerow(line)
示例12: write
# 需要导入模块: import csv [as 别名]
# 或者: from csv import writer [as 别名]
def write(self, filename):
with closing(open(filename + '.new', 'w')) as w:
c = csv.writer(w)
c.writerow(['bearing_start','bearing_end','bin_start','bin_end','samples','unique'])
for b_low,b_high,histo in self.values():
# make sure we write at least one value per sector,
# it makes things a little easier when plotting
first = True
for h_low,h_high,count,unique in histo.values():
if unique or first:
c.writerow(['%f' % b_low,
'%f' % b_high,
'%f' % h_low,
'%f' % h_high,
'%d' % count,
'%d' % unique])
first = False
os.rename(filename + '.new', filename)
示例13: outf_writer_compat
# 需要导入模块: import csv [as 别名]
# 或者: from csv import writer [as 别名]
def outf_writer_compat(outfile, encoding, errors, gzip_compress=False):
"""
Identify appropriate CSV writer given the Python version
"""
if compat.PY3:
if gzip_compress:
outf = gzip.open(outfile, 'wt', encoding=encoding, errors=errors)
else:
outf = open(outfile, 'w', encoding=encoding, errors=errors)
writer = csv.writer(outf)
else:
if gzip_compress:
outf = gzip.open(outfile, 'wb')
else:
outf = open(outfile, 'wb')
writer = compat.UnicodeWriter(outf, encoding=encoding, errors=errors)
return (writer, outf)
示例14: export
# 需要导入模块: import csv [as 别名]
# 或者: from csv import writer [as 别名]
def export(self, filename, render_func=None):
if not self.lineups:
return
total_players = 0
with open(filename, 'r') as csvfile:
lines = list(csv.reader(csvfile))
for i, lineup in enumerate(self.lineups, start=1):
if i >= len(lines):
lines.append([])
players_list = [(render_func or self.render_player)(player) for player in lineup.lineup]
if not total_players:
total_players = len(players_list)
lines[i] = players_list + lines[i][total_players:]
for line_order in range(i, len(lines) - 1):
lines[line_order] = [''] * total_players + lines[line_order][total_players:]
with open(filename, 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(lines)
示例15: create_csv_file
# 需要导入模块: import csv [as 别名]
# 或者: from csv import writer [as 别名]
def create_csv_file(cls, full_path_file, content, delimiter=','):
with open(full_path_file, 'w+') as u_file:
writer = csv.writer(u_file, quoting=csv.QUOTE_NONE, delimiter=delimiter)
writer.writerows(content)