Python写入和读取到txt、csv、excel和json文件

1.1 写入内容到txt中
# -*- coding: utf-8 -*-
import os
import numpy as np

# write txt
num = np.arange(12).reshape((3, 4))
output_dir = os.path.dirname(__file__)
filename = os.path.join(output_dir, 'abc.txt')
with open(filename, "w") as f:
    for i in range(0, len(num)):
        f.write(str(num[i]) + "\n")
    f.close()

结果展示:
在这里插入图片描述

1.2 读取txt内容
# 一起读取
fr = open(output_dir + '/abc.txt')
data = fr.read().splitlines()
print('一起读取:\n', data)

# 按行读取
lis = []
fr2 = open(output_dir + '/abc.txt')
for line in fr2.readlines():
    lis.append(line)
print('按行读取:\n', lis)

结果展示:
在这里插入图片描述

2.1 写入内容到csv或Excel
# -*- coding: utf-8 -*-
import os
import numpy as np
import pandas as pd

# generate dataset
num = np.arange(12).reshape((3, 4))
col = ['a', 'b', 'c', 'd']
data = pd.DataFrame(num, columns=col)
output_dir = os.path.dirname(__file__)

# write csv or Excel
data.to_csv(output_dir + '/abc2.csv', index=False)
data.to_excel(output_dir + '/abc2.xlsx', index=False, sheet_name='f1')

结果展示:
在这里插入图片描述

2.2 读取csv或Excel中内容
# read csv or Excel
data2 = pd.read_csv(output_dir + '/abc2.csv')
print('csv格式:\n', data2)
data3 = pd.read_excel(output_dir + '/abc2.xlsx', sheet_name='f1')
print('excel格式:\n', data3)

结果展示:
在这里插入图片描述

3.1 写入内容到json
# -*- coding: utf-8 -*-
import os
import json

# generate dataset
num = list(range(4))
col = ['a', 'b', 'c', 'd']
data = dict()
for i in range(len(col)):
    data.update({col[i]: num[i]})

output_dir = os.path.dirname(__file__)
filename = os.path.join(output_dir, 'abc.json')

# write json
json_file = json.dumps(data)
with open(filename, "w") as f:
    f.write(json_file)
    f.close()

结果展示:
在这里插入图片描述

3.2 读取json文件
# read json
fr3 = open(output_dir + '/abc.json')
json_file= json.load(fr3)
for i in json_file.keys():
    print('key: %s   value: %s' % (i, json_file[i]))

结果展示:
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值