获取文本内容的方法
- 方法一:使用open()内置函数
- 方法二:引用linecache包
文件tmp.txt内容如下
方法1.使用open()内置函数
import time
t1 = time.time()
file = open('tmp.txt','r')
content = file.read()
file.close()
lines = [x[1:-2].split('","') for x in content.split('\n')]
print(lines)
t2 = time.time()
print("用时 :%s" %(t2-t1))
执行结果:
[['ebc', 'acd', 'yde', 'cgd', 'by222'], ['cbc', 'ccd', 'hde', 'chd', 'by2p'], ['dbc', 'ecd', 'fde', 'cd4', 'b1yp'], ['cbc', 'ccd', 'hde', 'chd', 'by2p'], ['dbc', 'ecd', 'fde', 'cd4', 'b1yp'], ['ebc', 'acd', 'yde', 'cgd', 'by222'], ['cbc', 'ccd', 'hde', 'chd', 'by2p'], ['dbc', 'ecd', 'fde', 'cd4', 'b1yp'], ['ebc', 'acd', 'yde', 'cgd', 'by222'], ['cbc', 'ccd', 'hde', 'chd', 'by2p'], ['dbc', 'ecd', 'fde', 'cd4', 'b1yp'], ['ebc', 'acd', 'yde', 'cgd', 'by222'], ['cbc', 'ccd', 'hde', 'chd', 'by2p'], ['dbc', 'ecd', 'fde', 'cd4', 'b1yp'], ['ebc', 'acd', 'yde', 'cgd', 'by222'], ['']]
用时:0.0026924610137939453
方法2.引用linecache包
import linecache
import time
t1 = time.time()
f = linecache.getlines('tmp.txt')
# for x in f:
# lines.append(x[1:-2].split('","'))
lines = [x[1:-2].split('","') for x in f]
print(lines)
t2 = time.time()
print("用时 :%s" %(t2-t1))
执行结果:
[['ebc', 'acd', 'yde', 'cgd', 'by2222'], ['cbc', 'ccd', 'hde', 'chd', 'by2pp'], ['dbc', 'ecd', 'fde', 'cd4', 'b1ypp'], ['cbc', 'ccd', 'hde', 'chd', 'by2pp'], ['dbc', 'ecd', 'fde', 'cd4', 'b1ypp'], ['ebc', 'acd', 'yde', 'cgd', 'by2222'], ['cbc', 'ccd', 'hde', 'chd', 'by2pp'], ['dbc', 'ecd', 'fde', 'cd4', 'b1ypp'], ['ebc', 'acd', 'yde', 'cgd', 'by2222'], ['cbc', 'ccd', 'hde', 'chd', 'by2pp'], ['dbc', 'ecd', 'fde', 'cd4', 'b1ypp'], ['ebc', 'acd', 'yde', 'cgd', 'by2222'], ['cbc', 'ccd', 'hde', 'chd', 'by2pp'], ['dbc', 'ecd', 'fde', 'cd4', 'b1ypp'], ['ebc', 'acd', 'yde', 'cgd', 'by2222']]
用时:0.001079559326171875