10 examples of 'python save list to csv' in Python

Every line of 'python save list to csv' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
137def save_list_to_csv(list, filename):
138 f = open(filename, 'w')
139 writer = csv.writer(f, lineterminator='\n')
140 writer.writerows(list)
141 f.close()
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

5def save_dict_as_csv(data, filename, mode='w'):
6 """
7 Given nested dict `data`, write to CSV file
8 where rows are timesteps and columns are links/nodes as appropriate.
9
10 :param data: (dict) Nested dictionary of results data
11 :param filename: (string) Output CSV filename
12 :param mode: (string) file writing mode, 'w' for write, 'a' for append
13 in particular the annual optimization uses 'a' to append results each year.
14 :returns: nothing, but writes the output CSV file.
15 """
16 node_keys = sorted(data.keys())
17 time_keys = sorted(data[node_keys[0]].keys()) # add key=int for integer timesteps
18
19 writer = csv.writer(open(filename, mode))
20
21 if mode == 'w':
22 header = ['date'] + node_keys
23 writer.writerow(header)
24
25 for t in time_keys:
26 row = [t]
27 for k in node_keys:
28 if t in data[k] and data[k][t] is not None:
29 row.append(data[k][t])
30 else:
31 row.append(0.0)
32 writer.writerow(row)
4def dictionary_list_to_csv(dict_list):
5 keys = dict_list[0].keys()
6 csvfile = get_csv_file_name()
7 print("Gravando o arquivo " + csvfile)
8 with open(csvfile, "w") as output:
9 writer = csv.DictWriter(output, fieldnames=keys, lineterminator='\n')
10 writer.writeheader()
11 writer.writerows(dict_list)
290def dict_to_csv(data=None, filename='test.csv'):
291 r'''
292 Utility function to write a dictionary to a csv file
293 Uses dictionary keys as column headers
294 Data should all be same length
295 '''
296 data_list = [data[key] for key in data.keys()]
297 zipper = list(zip(*data_list))
298 with open(filename, 'w') as f:
299 w = csv.writer(f, lineterminator='\n')
300 w.writerow(data.keys())
301 w.writerows(zipper)
90def write_rows_to_csv(row_list, filename):
91 """
92 Write a list of namedtuple objects to a (unicode) CSV file.
93
94 Args:
95 row_list A list of namedtuple objects
96 Returns:
97 Raises:
98 """
99 with open(filename,'w') as out_file:
100 csv_file = UnicodeWriter(out_file, quoting=csv.QUOTE_ALL)
101 write_header = True
102 for row in row_list:
103 if write_header:
104 write_header = False
105 csv_file.writerow(list(row._fields))
106 csv_file.writerow([x for x in row._asdict().itervalues()])
25def write_dict_data_to_csv_file(csv_file_path, dict_data):
26 csv_file = open(csv_file_path, 'wb')
27 writer = csv.writer(csv_file, dialect='excel')
28
29 headers = dict_data[0].keys()
30 writer.writerow(headers)
31
32 # headers must be the same with dat.keys()
33 for dat in dict_data:
34 line = []
35 for field in headers:
36 line.append(dat[field])
37 writer.writerow(line)
38
39 csv_file.close()
305def to_csv(self, f):
306 is_path = False
307 if isinstance(f, str):
308 is_path = True
309 f = open(f, mode='w')
310 writer = csv.DictWriter(f, self.columns)
311 writer.writerows(self._data)
312 if is_path:
313 f.close()
20def ToCsv(self,name='FileName.csv', DataToWrite=[
21 ["First", "Second", "Third"], ]):
22 #Write DataResult to CSV file
23 with open(name, 'w', newline='') as fp:
24 a = csv.writer(fp, delimiter=',')
25 a.writerows(DataToWrite)
146def dump_csv(file_name):
147 global var_list
148 keys = sorted(var_table.keys(), key=int)
149
150 with open(file_name, mode='w') as fd:
151 fd.write(','.join(var_list) + '\n');
152 for ind in keys:
153 entry = var_table[ind]
154 dispatch_number = entry['Index']
155 if ind != dispatch_number: fatal("Dispatch #" + ind + " index mismatch (" + dispatch_number + ")\n")
156 val_list = [entry[var] for var in var_list]
157 fd.write(','.join(val_list) + '\n');
349def saveToCsv(self):
350 """保存表格内容到CSV文件"""
351 # 先隐藏右键菜单
352 self.menu.close()
353
354 # 获取想要保存的文件名
355 path = QtGui.QFileDialog.getSaveFileName(self, '保存数据', '', 'CSV(*.csv)')
356
357 try:
358 if not path.isEmpty():
359 with open(unicode(path), 'wb') as f:
360 writer = csv.writer(f)
361
362 # 保存标签
363 headers = [header.encode('gbk') for header in self.headerList]
364 writer.writerow(headers)
365
366 # 保存每行内容
367 for row in range(self.rowCount()):
368 rowdata = []
369 for column in range(self.columnCount()):
370 item = self.item(row, column)
371 if item is not None:
372 rowdata.append(
373 unicode(item.text()).encode('gbk'))
374 else:
375 rowdata.append('')
376 writer.writerow(rowdata)
377 except IOError:
378 pass

Related snippets