Python文字處理幾種方法
阿新 • • 發佈:2019-01-04
Python文字處理幾種方法
方法一:readline函式
#-*- coding: UTF-8 -*- f = open("D:\pythontest\splm_ugslmd.log") line = f.readline() while line: print(line, end = '') line = f.readline() f.close()
優點:節省記憶體,不需要一次性把資料讀取到記憶體中。
缺點:速度相對較慢。
方法二:一次讀取多行資料
#-*- coding: UTF-8 -*- f = open("D:\pythontest\splm_ugslmd.log") while 1: lines = f.readlines(10000) if not lines: break for line in lines: print(line) f.close()
優點:一次性把10000條資料讀取到記憶體中。
缺點:速度相對較快。
方法三:直接for迴圈
#-*- coding: UTF-8 -*- for line in open("D:\pythontest\splm_ugslmd.log"): #print line, #python2 print(line)
方法四:使用fileinput模組
import fileinput for line in fileinput.input("D:\pythontest\splm_ugslmd.log"): print(line)