内置函数文件读取
- 通常我们在读取文件的时候,会用到read(), readline(), readlines()。
read ()的方法是一次性把文件的内容以字符串的方式读到内存, 放到一个字符串变量中
readlines()的方法是一次性读取所有内容, 并按行生成一个list
因为read()和readlines()是一次性把文件加载到内存, 如果文件较大, 甚至比内存的大小还大, 内存就会爆掉。 所以,这两种方法只适合读取小的文件。
def test():
f = open("/tmp/test.log", "r")
print f.read()
f.close()
f = open("/tmp/test.log", "r")
for line in f.readlines():
print line
f.close()
- 实际工作中,会碰到读取10几G的大文件的需求, 比如说日志文件。 这时候就要用的新的读取文件的方法: 就是利用到生成器generator。
- 将文件切分成小段,每次处理完小段内容后,释放内存,这里会使用yield生成自定义可迭代对象, 即generator, 每一个带有yield的函数就是一个generator。
def read_in_block(file_path):
BLOCK_SIZE = 64*10000
with open(file_path, "r") as f:
while True:
block = f.read(BLOCK_SIZE) # 每次读取固定长度到内存缓冲区
if block:
yield block
else:
return # 如果读取到文件末尾,则退出
def test():
file_path = "/tmp/test.log"
for block in read_in_block(file_path):
print block
- 利用open(“”, “”)系统自带方法生成的迭代对象
def test():
with open("/tmp/test.log") as f:
for line in f:
print line
for line in f 这种用法是把文件对象f当作迭代对象, 系统将自动处理IO缓冲和内存管理, 这种方法是更加pythonic的方法。 比较简洁。
利用Pandas函数
import pandas as pd
def read_data(file_name):
'''
file_name:文件地址
'''
inputfile = open(file_name, 'rb') #可打开含有中文的地址
data = pd.read_csv(inputfile, iterator=True)
loop = True
chunkSize = 1000 #一千行一块
chunks = []
while loop:
try:
chunk = data.get_chunk(chunkSize)
chunks.append(chunk)
except StopIteration:
loop = False
print("Iteration is stopped.")
data = pd.concat(chunks, ignore_index=True)
#print(train.head())
return data