我很想检查更多关于性能的信息,我使用了 Martijn Pieters 和 Stephen Miller 的答案。
我尝试了带shutil
和不带的二进制和文本模式shutil
。我试图合并 270 个文件。
文本模式 -
def using_shutil_text(outfilename):
with open(outfilename, 'w') as outfile:
for filename in glob.glob('*.txt'):
if filename == outfilename:
# don't want to copy the output into the output
continue
with open(filename, 'r') as readfile:
shutil.copyfileobj(readfile, outfile)
def without_shutil_text(outfilename):
with open(outfilename, 'w') as outfile:
for filename in glob.glob('*.txt'):
if filename == outfilename:
# don't want to copy the output into the output
continue
with open(filename, 'r') as readfile:
outfile.write(readfile.read())
二进制模式 -
def using_shutil_text(outfilename):
with open(outfilename, 'wb') as outfile:
for filename in glob.glob('*.txt'):
if filename == outfilename:
# don't want to copy the output into the output
continue
with open(filename, 'rb') as readfile:
shutil.copyfileobj(readfile, outfile)
def without_shutil_text(outfilename):
with open(outfilename, 'wb') as outfile:
for filename in glob.glob('*.txt'):
if filename == outfilename:
# don't want to copy the output into the output
continue
with open(filename, 'rb') as readfile:
outfile.write(readfile.read())
二进制模式的运行时间 -
Shutil - 20.161773920059204
Normal - 17.327500820159912
文本模式的运行时间 -
Shutil - 20.47757601737976
Normal - 13.718038082122803
看起来在两种模式下,shutil 执行相同,而文本模式比二进制更快。
操作系统:Mac OS 10.14 Mojave。MacBook Air 2017。