python普通文件读写
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
常用的参数有文件路径file和读写模式mode
字符 | 含义 |
---|---|
‘r’ | 只读模式(默认) |
‘w’ | 只写模式 |
‘a’ | 追加写模式 |
‘b’ | 二进制模式 |
‘t’ | 文本模式(默认) |
‘+’ | 更新模式(一般和其他模式并用) |
打开的文件描述符有以下几个常用的函数
读写函数
read & write
f = open(yourfilepath, 'r')
ss = f.read() # 读进文件的全部内容返回一个字符串
ss = f.read(1024) # 读取指定字节的内容返回一个字符串
line = f.readline() # 读取文件的一行返回字符串(包含换行符)
line = line.strip("\n") # 处理的时候一般要去掉换行符(这里是\n)
lines = f.readlines() # 读取所有行返回一个列表list,每个元素(类型为字符串)为文件的一行
for line in f.readlines():
pass
f.close() # 文件用完要记得关闭,可以用with关键字,不用手动关闭,程序会自动关闭
# 以下均用with来读写文件
with open('yourfilepath', 'w') as tmpf:
a = 100; b = 97.5; c = 'Good'
tmpf.write('number=%d score=%f result%s' % (a, b, c))
# 或者直接写入文件内容——字符串(或二进制数据)
ss = 'yourstring'
f.write(ss) # 直接写入
ss = 'yourstring'
f.writeline(ss) # 写入时会自动加入换行符
ss = ['a', 'b', 'c']
f.writelines(ss) # 参数为字符串序列
python大文件读写
内置方法
大文件读写的时候如果使用上面的函数内存分分钟会爆掉,需要使用python的生成器
open函数返回的其实还是一个生成器,不管文件多大,可以一行一行读取
with open(yourfilepath,'r') as f:
for line in f:
pass # 对每行做处理
pandas
pandas的read_csv函数可以分块读取数据
### 分批加载训练集
chunksize = 10000
reader = pd.read_table(yourfile, chunksize=chunksize)
for line in reader:
pass # 对每行做处理
# 或者使用iterator获得迭代对象
reader = pd.read_table(yourfile, iterator=True)
loop = True
while loop:
try:
chunk = reader.get_chunk(chunkSize)
pass # 对每行做处理
except StopIteration:
loop = False
分块生成批量数据
在深度学习中,经常需要送入批量数据,可以使用生成器来完成
import numpy as np
import pandas as pd
# batch_size为皮尺寸
# datapath为数据集路径
# labelpath标签路径
def data_iter(batch_size, datapath, labelpath):
train_x = pd.read_csv(datapath)
train_y = pd.read_csv(labelpath)
while(1): # 死循环,因为数据要循环读取,epoch的缘故
nb_batch = np.ceil(train_x.shape[0] * 1.0 / batch_size)
for i in range(int(nb_batch)):
start = i*batch_size
end = min((i+1)*batch_size, train_x.shape[0])
# 生成器生成需要的数据(X,Y)
yield (train_x[start:end], train_y[start:end])
参考网站
1 使用Python Pandas处理亿级数据
2 pandas.read_csv——分块读取大文件
3 pandas.read_csv参数整理
4 The Python Standard Library I/O
5 强悍的 Python —— 读取大文件
6 python:open函数的使用方法
7 Python读写文件
8 python 如何读取大文件
9 Python linecache模块缓存读取大文件指定行
10 python读文件的三个方法read()、readline()、readlines()详解