import csv
'''
普通方式读取csv文件
'''
def read_csv():
with open('example.csv', 'r') as file:
reader = csv.reader(file) # 返回可迭代对象, 只可被遍历一次
# for row in list(reader): # 返回一个二维数组
# print(row)
for row in reader: # 可使用.next获取一行数据
print(reader.line_num, row)
'''
以字典的形式读取csv文件
'''
def read_to_dict():
with open('example.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
print(row)
'''
导出csv数据 - Dict形式
'''
def export_with_Dict():
fieldName = ['name', 'age']
data = [
{'name': 'Mike', 'age': 12},
{'name': 'Jack', 'age': 13},
{'name': 'Bob', 'age': 14},
{'name': 'Tom', 'age': 15},
]
with open('example.csv', 'w', newline = '') as file:
writer = csv.DictWriter(file, fieldnames = fieldName)
writer.writeheader()
for row in data:
writer.writerow(row)
# 写入多行 writer.writerrows(data)
print('export success')
'''
导出csv数据 - List形式
'''
def export_with_list():
data = [
['name', 'age'],
['Mike', 12],
['Jack', 13],
['Jerry', 14],
]
with open('exmplae.csv', 'w', newline = '') as file:
writer = csv.writer(file)
for row in data:
writer.writerow(row)
# 写入多行 writer.writerows(data)
if __name__ == '__main__':
pass
Python处理csv文件
最新推荐文章于 2023-04-13 22:32:10 发布