python脚本将目录中的所有文件连接到一个fi中

2024-09-27 07:23:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了以下脚本,将目录中的所有文件连接到一个文件中。

这可以优化吗

  1. 惯用的python

  2. 时间

以下是片段:

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")

Tags: 文件intxtfortimeaswithopen
3条回答

使用^{}复制数据:

import shutil

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)

shutil以块的形式读取readfile对象,并将它们直接写入outfile文件对象。不要使用readline()或迭代缓冲区,因为您不需要查找行结尾的开销。

在读和写时使用相同的模式;这在使用Python 3时尤为重要;我在这里都使用了二进制模式。

使用Python2.7,我对

outfile.write(infile.read())

shutil.copyfileobj(readfile, outfile)

我迭代了20多个.txt文件,大小从63MB到313MB不等,联合文件大小约为2.6GB。在这两种方法中,普通读取模式的性能都优于二进制读取模式,shutil.copyfileobj通常比outfile.write快。

当比较最差组合(outfile.write,二进制模式)和最佳组合(shutil.copyfileobj,正常读取模式)时,差异非常显著:

outfile.write, binary mode: 43 seconds, on average.

shutil.copyfileobj, normal mode: 27 seconds, on average.

在正常读取模式下,输出文件的最终大小为2620 MB,而在二进制读取模式下为2578 MB。

不需要使用那么多变量。

with open(outfilename, 'w') as outfile:
    for fname in filenames:
        with open(fname, 'r') as readfile:
            outfile.write(readfile.read() + "\n\n")

相关问题 更多 >

    热门问题