前言
好了,大家可能会有疑惑,python不是学了好久吗,为何突然今天写这篇文章呢。
其实之前就想写一个python读写文件专题的,然后没写成。今天突然兴起,想开个头,以后慢慢更新。
本文为了方便自己和大家在使用python读写文件的时候方便查阅语法的使用。
刚接触python的朋友可以先看看这篇Python环境配置与入门建议(面向新手文)
读写txt文件
读txt文件
with open("files/1.txt", "r", encoding='utf-8') as f: # 打开文件
data = f.read() # 读取文件
print(data)
print(type(data))
可以看到是字符串类型,但是通常我更喜欢换返回的是列表类型:
with open("files/1.txt", "r", encoding='utf-8') as f: # 打开文件
data = f.readlines() # 读取文件
print(data)
print(type(data))
写txt文件
写入一行的话,
with open('files/2.txt', 'w', encoding='utf-8') as f:
f.write('hhh')
如果想写入多行:
lt = ['This', 'is', 'a', 'big', 'program']
lt = [i + '\n' for i in lt]
with open('files/2.txt', 'w', encoding='utf-8') as f:
f.writelines(lt)
读写csv文件
读csv文件
读取example.csv文件: (这里也可以替代为其他路径的文件,但是要稍微注意一下当前的目录比如你import os,然后os.getcwd()看看是不是和你想的目录一样的)
import csv
with open('example.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
ls = list(reader)
这样csv文件中的数据就都在 ls 中了。
写csv文件
import csv
import string
a = list(string.ascii_lowercase)
b = list(string.ascii_uppercase)
c = list(string.digits)
d = ['汉语', '数学', '英语', '物理']
l = [a, b, c, d]
with open('test.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
# 可以用下面这句writerows,相当于for 循环调用writerow, 效果一样
# writer.writerows(l)
for i in l:
writer.writerow(i)
pandas读取csv文件
import pandas as pd
data = pd.read('data/train.csv')
# 查看头几行,默认为5
data.head()
pandas在数据分析经常用到,有兴趣可以去看看之前一篇博客pandas基础常用用法总结
读写json文件
写json文件
来看个小例子
import json
grade_json = [{
'name': 'Li Ming',
'grade': {
'语文': 90,
'数学': 100,
'英语': 97
}},
{
'name': 'Lisa',
'grade': {
'语文': 99,
'数学': 96,
'英语': 99
}}]
with open('files/test.json', 'w', encoding='utf-8') as f:
json.dump(grade_json, f, ensure_ascii=False)
其中,ensure_ascii=False是确保中文字符串不会被转码。
读json文件
我们再来把刚刚写入的文件读一下
import json
with open('files/test.json', 'r', encoding='utf-8') as f:
grade_read_from_json = json.load(f)
print(grade_read_from_json)
print(type(grade_read_from_json))
可以看到将原来的json文件读出来了。