更高效:使用open(文件,“wb”):pass或os.remove(file)

时间:2014-01-14 17:07:33

标签: python performance

我有一种情况,我反复清除文件,以便子进程中的另一个(闭源)程序可以在其开头写入,乘以几个线程。

我的问题是更好(资源消耗更少):

with open(file, 'wb') as wf:
    pass

或者,简单地说:

os.remove(file)

因为子进程将会出现并打开或创建并打开文件,这取决于我使用的是哪一个。

1 个答案:

答案 0 :(得分:1)

看起来清空文件的速度稍微快一些,但不是很多。注意我没有使用子进程来调用外部命令,因为我假设大部分差异将是filesystem或os

import os
from timeit import timeit

def remove():
    os.remove('test.txt')
    external_command()

def empty():
    open('test.txt', 'wb').close()  # same as your with statement, but shorter
    external_command()

def external_command():
    ''' not actually an external command, but pretend... '''
    with open('test.txt', 'a') as f:
        f.write('mooo')


print 'removal took', timeit(remove, number=1000), 'seconds'
#O: removal took 0.132004915145 seconds

print 'emptying took', timeit(empty, number=1000), 'seconds'
#O: emptying took 0.106063604726 seconds