文件存取的格式:
r: 读取文件,若文件不存在则会报错
w: 写入文件,若文件不存在则会先创建再写入,会覆盖原文件
a : 写入文件,若文件不存在则会先创建再写入,但不会覆盖原文件,而是追加在文件末尾
rb,wb:分别于r,w类似,但是用于读写二进制文件
r+: 可读、可写,文件不存在也会报错,写操作时会覆盖
w+: 可读,可写,文件不存在先创建,会覆盖
a+: 可读、可写,文件不存在先创建,不会覆盖,追加在末尾
import csv
文件路径+文件名:file_path_csv = r"F:\practice\file\lianxi.csv"
读取时候字典的键:read_filedname = ["aaa", "bbb", "ccc", "ddd","eee","fff"]
写入时候字典的键write_filedname = ["书名","作者","出版单位","出版时间","价格","评价人数"]
写入时候字典的值:content = [1,2,3,4,5,6]
#写入字典格式
def dict_write(path_csv,Format,content):
with open(path_csv,Format,newline='') as f:
#按字典格式写入
f_csv = csv.DictWriter(f,fieldnames = write_filedname)
#写入表头
f_csv.writeheader()
#按照字典写入
f_csv.writerow({ write_filedname[0]:content[0],
write_filedname[1]:content[1],
write_filedname[2]:content[2],
write_filedname[3]:content[3],
write_filedname[4]:content[4],
write_filedname[5]:content[5]})
#默认将CSV文件的第一列作为字典的键
def dict_read1(path_csv):
with open(path_csv) as f:
reader = csv.DictReader(f)
items = list(reader)
return items
#指定字典的键,第一列也为数据
def dict_read2(path,fieldnames):
with open(path) as f:
reader = csv.DictReader(f,fieldnames=fieldnames)
items = list(reader)
return items
#遍历字典模式读出的数据
def dict_read(items):
for item in items:
for i in item:
print(i+":"+item[i])
代码开始执行的地方(主函数 )
if __name__ == '__main__':
#dict_write(file_path_csv,"w",content)
#items = dict_read2(file_path_csv,read_filedname)
items = dict_read1(file_path_csv)
dict_read(items)