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()

结果展示:
Python写入和读取到txt、csv、excel和json文件_第1张图片

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)

结果展示:
Python写入和读取到txt、csv、excel和json文件_第2张图片

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

结果展示:
Python写入和读取到txt、csv、excel和json文件_第3张图片

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)

结果展示:
Python写入和读取到txt、csv、excel和json文件_第4张图片

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()

结果展示:
Python写入和读取到txt、csv、excel和json文件_第5张图片

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]))

结果展示:
Python写入和读取到txt、csv、excel和json文件_第6张图片

你可能感兴趣的:(数据处理篇,python,excel,json)