[英]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.