我有2个或更多.txt文件包含
file1.txt
India
File2.txt
US
我想在第三个文件中写输出为India US。 请任何人都可以告诉我如何使用python。
答案 0 :(得分:1)
import glob
all_text_files = glob.glob('/path/to/dir', '*.txt')
with open('output_file.txt', 'w') as fh:
for text_file in all_text_files:
data = open(text_file, 'r')
fh.write(data.read())
glob.glob('*.txt')
返回当前目录中的所有.txt
个文件。
如果您只想读取几个文件,可以在列表中指定它们
all_text_files = ['file1.txt', 'file2.txt', ....., 'filen.txt']
答案 1 :(得分:0)
source_files = ['file1.txt', 'file2.txt']
with open('output.txt', 'w') as fh_out:
for fname in source_files:
with open(fname, 'r') as fh:
fh_out.write(fh.read())
答案 2 :(得分:0)
files = ['file1.txt','file2.txt']
for file in files:
with open(file,'r') as file_read:
with open('file3.txt', 'w+') as file_put:
file_put.write(file_read.read())