我编写了以下脚本,将目录中的所有文件连接到一个文件中。
这可以优化吗
惯用的python
时间
以下是片段:
import time, glob
outfilename = 'all_' + str((int(time.time()))) + ".txt"
filenames = glob.glob('*.txt')
with open(outfilename, 'wb') as outfile:
for fname in filenames:
with open(fname, 'r') as readfile:
infile = readfile.read()
for line in infile:
outfile.write(line)
outfile.write("\n\n")
使用^{} 复制数据:
shutil
以块的形式读取readfile
对象,并将它们直接写入outfile
文件对象。不要使用readline()
或迭代缓冲区,因为您不需要查找行结尾的开销。在读和写时使用相同的模式;这在使用Python 3时尤为重要;我在这里都使用了二进制模式。
使用Python2.7,我对
对
我迭代了20多个.txt文件,大小从63MB到313MB不等,联合文件大小约为2.6GB。在这两种方法中,普通读取模式的性能都优于二进制读取模式,shutil.copyfileobj通常比outfile.write快。
当比较最差组合(outfile.write,二进制模式)和最佳组合(shutil.copyfileobj,正常读取模式)时,差异非常显著:
在正常读取模式下,输出文件的最终大小为2620 MB,而在二进制读取模式下为2578 MB。
不需要使用那么多变量。
相关问题 更多 >
编程相关推荐