【问题标题】:Combine specific files and put it in a single file python合并特定文件并将其放在单个文件中 python
【发布时间】:2014-02-07 15:41:03
【问题描述】:

我是 python 新手。 我的目录中有两个文件 text1.txt 和 text2.txt。我需要合并 text1 和 text2 中的数据并将结果打印到 result.txt 中。

例如:

text1.txt

a                              
b               
c

text2.txt

aa                                                                                                            bb
cc

结果.txt

a
b
c
aa
bb
cc 

(一个在另一个之下)

现在,我知道一个脚本可以通过声明全局来组合所有文件 .txt

import glob
files = glob.glob( '*.txt' )

with open( 'result.txt', 'w' ) as result:
    for file_ in files:
        for line in open( file_, 'r' ):
            result.write( line )

但我有很多以 .txt 结尾的文件,我想要特定的文件。

任何帮助将不胜感激。

【问题讨论】:

    标签: python file concatenation


    【解决方案1】:

    这将避免解析换行符,因此只要每个文件都适合内存并以换行符结尾,可能会更快。

    from itertools import chain
    
    files = ['text1.txt', 'text2.txt']
    with outfile as open('result.txt', 'w'):
        outfile.write(chain.from_iterable(open(f).read() for f in files)
    

    【讨论】:

      【解决方案2】:

      只需创建要从中复制的文件的列表。

      files = ['text1.txt', 'text2.txt']
      
      with open('result.txt', 'w') as result:
          for file_ in files:
              for line in open(file_, 'r'):
                  result.write(line)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-28
        • 1970-01-01
        相关资源
        最近更新 更多