程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

python数据文件读写

发布于2019-08-07 16:48     阅读(962)     评论(0)     点赞(0)     收藏(4)


CSV格式读写

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'})

json格式读写

python内置json包提供了四个函数:dumps、dump、loads、load。不带s的负责文件与字典的转换。带s的负责字符串和字典的转换。

字典到字符串 string json.dumps(dict)

import json

test_str = json.dumps({'name' : "cat"})

字符串到字典 dict json.loads(string)

import json

test_dict = json.loads("{'name' : "cat"}")

字典到json文件 json.dump(dict, file)

import json

with open("test.json","w") as f:
    json.dump({'name' : "cat"}, f)

json文件到字典 dict json.load(file)

import json

with open("test.json",'r') as f:
    test_dict = json.load(f)


所属网站分类: 技术文章 > 博客

作者:我想打人

链接:https://www.pythonheidong.com/blog/article/11743/e13529e510960edf2147/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

0 0
收藏该文
已收藏

评论内容:(最多支持255个字符)