wss1051 发表于 2018-8-9 06:13:40

python处理大文件的内存问题

  摘要:
  同学们时常会遇到要处理大文件的情况,现在是大数据时代,有些文件动辄几十个G,我们在处理这样文件的时候一不小心就把内存撑爆了,或者程序被强制kill掉了。
  原因是你一次性把文件的所有内容都读取到内存里面了。python里面有方法可以一段一段的读文件。
  正文:
  没错,就是用iterator,又叫迭代器,实例代码如下。
  cat test.py
  f = open('data', 'r')
  for line in f:
  line = line.split(";;")
  lines.append(line)
  if len(lines) >= 10000:
  # consume the lines which have been read
  print lines
  del lines[:]
  if lines:
  # consume the lines which have been read
  print lines
  cat data
  73231701-201610;;shop_id::::73231701;;shop_name::::邂逅魅影;;platform_name::::xxxx;;shop_type::::个人卖家;;shop_loc::::xxx;;gold_seller::::否;;market_name::::taobao;;description::::NULL;;service::::NULL;;logistics::::NULL;;shop_owner::::洋洋103105;;create_time::::2012-08-15;;credit::::爱心4;;shop_age::::4;;co_name::::NULL;;shop_link::::https://shop73231701.example.com
  73295319-201610;;shop_id::::73295319;;shop_name::::唯美为你最美;;platform_name::::xxxx;;shop_type::::个人卖家;;shop_loc::::xxx;;gold_seller::::否;;market_name::::taobao;;description::::NULL;;service::::NULL;;logistics::::NULL;;shop_owner::::chenyan121166563;;create_time::::2012-08-20;;credit::::钻石3;;shop_age::::4;;co_name::::NULL;;shop_link::::
  https://shop73295319.example.com
  上面的文件实际会很长,我这里只是写了两行,仅供参考。
  “for line in f”每次都只会读取一行数据到内存,我们可以设置一个buffer,比如每10000行用list暂存下,处理完了之后再继续读取文件。
  这样就实现了一段一段的读取文件内容到内存。是不是很酷!
  赶紧试试吧!
页: [1]
查看完整版本: python处理大文件的内存问题