关于os.chdir(path)位置对程序的影响,
import os import time
#直接把path放到open()里面 def fu0(): star = time.time() for i in range(100): p = os.listdir('E:/pythontxt/PDF文字提取/') for each in p: with open('E:/pythontxt/PDF文字提取/'+each,'rb') as o: o.readline() print('完成') end = time.time() print(end - star)
#os.chdir(path)放到最里层的for
def fu1(): star = time.time() for i in range(100): p = os.listdir('E:/pythontxt/PDF文字提取/') for each in p: os.chdir('E:/pythontxt/PDF文字提取/') with open(each,'rb') as o: o.readline() print('完成') end = time.time() print(end - star)
#os.chdir(path)放到次层的for
def fu2():
star = time.time() for i in range(100): os.chdir('E:/pythontxt/PDF文字提取/') p = os.listdir('E:/pythontxt/PDF文字提取/') for each in p: with open(each,'rb') as o: o.readline() print('完成') end = time.time() print(end - star)
#os.chdir(path)放到最外层的for
def fu3(): star = time.time() os.chdir('E:/pythontxt/PDF文字提取/') for i in range(100): os.chdir('E:/pythontxt/PDF文字提取/') p = os.listdir('E:/pythontxt/PDF文字提取/') for each in p: with open(each,'rb') as o: o.readline() print('完成') end = time.time() print(end - star)
#每个运行2次估计平均值 fu0() fu0() fu1() fu1() fu2() fu2() fu3()
fu3()
#先在文件夹下写1000个txt
import os os.chdir('E:/pythontxt/PDF文字提取/') for i in range(1000): with open(str(i)+'.txt','w') as o: o.write(str(i))
结果
完成
6.512665510177612
完成
6.204932689666748
完成
10.26894736289978
完成
10.360546112060547
完成
5.979380369186401
完成
5.968496799468994
完成
5.956638336181641
完成
5.928236722946167
fu0():可以看出直接把path写到open()中速度比较快,
fu1():os.chdir(path)放到最里层的for中 速度最慢,存在反复执行os.chdir(path);
fu2()和fu3()差别不大略比fu0()快一丢丢,是应为for只进行了100个循环,当循环数大了fu3()比fu2()节省时间;
所以一般不要把一些不需要调用的放到for中,当循环数大了就影响运行速度