首页 > 代码库 > Python-csv模块读写csv文件

Python-csv模块读写csv文件


import csv
# 采用DictReader进行读写:

# 读csv文件
def get_data(self, from_file):
test_data = http://www.mamicode.com/[]

with open(from_file, ‘rb‘) as csv_file:
csv.register_dialect(‘read‘, delimiter=\t, quoting=csv.QUOTE_NONE)
reader = csv.DictReader(csv_file, dialect=read‘)
for row in reader:
test_data.append(row)
return test_data

# 写csv文件
def set_data(self, to_file, field_names, data):
with open(to_file, ‘wb‘) as csv_file:
csv.register_dialect(‘write‘, quoting=csv.QUOTE_ALL)
writer = csv.DictWriter(csv_file, fieldnames=field_names, dialect=write‘)
writer.writeheader()

for row in data:
writer.writerow(row)

Python-csv模块读写csv文件