简体   繁体   English

合并特定文件并将其放在单个文件python中

[英]Combine specific files and put it in a single file python

I'm new to python. 我是python的新手。 I have two files text1.txt and text2.txt in my directory. 我的目录中有两个文件text1.txt和text2.txt。 I need to combine the data from text1 and text2 and print the result in result.txt. 我需要合并来自text1和text2的数据,并将结果打印在result.txt中。

For Example: 例如:

text1.txt text1.txt

a                              
b               
c

text2.txt text2.txt

aa                                                                                                            bb
cc

result.txt 的Result.txt

a
b
c
aa
bb
cc 

(All one below the other) (所有一个都在另一个下面)

Now, I know a script to combine all the files .txt by declaring the global 现在,我知道了一个通过声明全局来合并所有文件.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 )

but I have a lot of files that end with .txt and I want specific files. 但是我有很多以.txt结尾的文件,我想要特定的文件。

Any help would be highly appreciated. 任何帮助将不胜感激。

This will avoid parsing the newlines, so may be faster as long as each file fits into memory and ends with a newline. 这将避免解析换行符,因此,只要每个文件都适合内存并以换行符结尾,它可能会更快。

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)

Just create a list of the files you want to copy from. 只需创建要从中复制文件的列表即可。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 python 从多个 excel 文件中读取和组合特定行到单个文件中? - How to read & combine specific rows from multiple excel files into a single file using python? 按日期将文件合并为一个文件 - Combine files into a single file by date Python-合并文本文件(特定行) - Python - combine text files (specific lines) 如何通过sql或python将行合并到dataframe中的单行中 - How to combine rows and put into single row in dataframe by sql or python 在matplotlib(python)或LaTeX中将多个pdf文件作为一个单独的pdf文件进行绘图/组合 - Plot/combine multiple pdf files as one single pdf file in matplotlib (python) or LaTeX 如何将多个.pcd 文件组合成一个包含点云数据(python)的单个.pcd 文件? - How to combine multiple .pcd files into a single .pcd file which contains point cloud data (python)? python将两个文本文件合并到一个文件中 - python combine two text files to one file 将多个CSV文件中的列合并为一个文件 - Combine columns from several CSV files into a single file 如何将多个泡菜文件放在一个泡菜文件中 - How to put multiple pickles files in a single pickle file 如何通过解析导入来合并并获得单个Python文件 - How to combine and get a single Python file by resolving the imports
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM