文件操作
1.大数据的文件读取
- 读取文件时,如果文件过大,则一次读取全部内容到内存,容易造成内存不足,所以要对大文件进行批量的读取内容。
- python读取大文件通常两种方法:第一种是利用yield生成器读取;第二种是:利用open()自带方法生成迭代对象,这个是一行一行的读取。
def read_big_file(file_path, size=1024, encoding='utf-8'):
with open(file_path, 'r', encoding=encoding) as f:
while True:
part = f.read(size)
if part:
yield part
else:
return None
file_path = 'data/big_data.txt'
size = 100
for part in read_big_file(file_path, size):
with open('data/new_big_data.txt', 'a', encoding='utf-8') as w:
w.write(part)
print(part)
print('*' * 100)
file_path = 'data/big_data.txt'
new_file_path = 'data/new_big_data.txt'
with open(file_path, 'r', encoding='utf-