发布于2019-08-07 16:48 阅读(1107) 评论(0) 点赞(0) 收藏(4)
Comma-Separated Values 有时也称为字符分隔值,因为分隔字符也可以不是逗号。以
,
分隔的文件叫csv,以\t
分隔的叫tsv
import csv
data=[]
with open(r'data.csv',) as csvfile:
file_list = csv.reader(csvfile,'mydialect')
for line in file_list:
data.append(line)
print(data)
如果文件是其他分隔符,如
\n
,则需要传入分隔符类型。
import csv
data=[]
with open(r'data.csv',) as csvfile:
file_list = csv.reader(csvfile,delimiter='\t')
for line in file_list:
data.append(line)
print(data)
import csv
with open('data.csv','r',encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
# 读取出的内容是列表格式的
print(row,type(row),row[1])
import csv
with open('data.csv','r',encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
# 读取的内容是字典格式的
print(row['last_name'])
import csv
with open('data.csv','a+',encoding='utf-8',newline='') as csvfile:
writer = csv.writer(csvfile)
# 写入一行
writer.writerow(['1','2','3','4','5','5','6'])
# 写入多行
writer.writerows([[0, 1, 3], [1, 2, 3], [2, 3, 4]])
import csv
with open('data.csv','a+',encoding='utf-8',newline='') as csvfile:
filename = ['first_name','last_name']
# 写入列标题
writer = csv.DictWriter(csvfile,fieldnames=filename)
writer.writeheader()
writer.writerow({'first_name':'wl','last_name':'wtx'})
writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
python内置json包提供了四个函数:dumps、dump、loads、load。不带s的负责文件与字典的转换。带s的负责字符串和字典的转换。
import json
test_str = json.dumps({'name' : "cat"})
import json
test_dict = json.loads("{'name' : "cat"}")
import json
with open("test.json","w") as f:
json.dump({'name' : "cat"}, f)
import json
with open("test.json",'r') as f:
test_dict = json.load(f)
作者:我想打人
链接:https://www.pythonheidong.com/blog/article/11743/e13529e510960edf2147/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!