如何使用python将指定目录中的所有文本文件合并为一个文本文件,并使用相同的文件名重命名输出文本文件。
例如:Filea.txt和Fileb_2.txt在根目录中,并且输出生成的文件为Filea_Fileb_2.txt
Filea.txt
123123
21321
Fileb_2.txt
2344
23432
Filea_Fileb_2.txt
123123
21321
2344
23432
我的脚本:
PWD1 = /home/jenkins/workspace
files = glob.glob(PWD1 + '/' + '*.txt')
with open(f, 'r') as file:
for line in (file):
outputfile = open('outputfile.txt', 'a')
outputfile.write(line)
outputfile.close()
答案 0 :(得分:2)
这是组合文本文件的另一种方法。
#! python3
from pathlib import Path
import glob
folder_File1 = r"C:\Users\Public\Documents\Python\CombineFIles"
txt_only = r"\*.txt"
files_File1 = glob.glob(f'{folder_File1}{txt_only}')
new_txt = f'{folder_File1}\\newtxt.txt'
newFile = []
for indx, file in enumerate(files_File1):
if file == new_txt:
pass
else:
contents = Path(file).read_text()
newFile.append(contents)
file = open(new_txt, 'w')
file.write("\n".join(newFile))
file.close()
答案 1 :(得分:1)
这是一个可行的解决方案,它将文件名和文件内容都存储在列表中,然后加入列表文件名并创建“组合”文件名,然后将所有文件的内容添加到其中,因为列表按顺序追加读取数据就足够了(我的示例文件名是filea.txt和fileb.txt,但它适用于您使用的文件名):
import os
import sys
path = sys.argv[1]
files = []
contents = []
for f in os.listdir(path):
if f.endswith('.txt'): # in case there are other file types in there
files.append(str(f.replace('.txt', ''))) #chops off txt so we can join later
with open(f) as cat:
for line in cat:
contents.append(line) # put file contents in list
outfile_name = '_'.join(x for x in files)+'.txt' #create your output filename
outfile = open(outfile_name, 'w')
for line in contents:
outfile.write(line)
outfile.close()
要在特定目录上运行此命令,只需在命令行中将其传递:
$python3.6 catter.py /path/to/my_text_files/
输出文件名:
filea_fileb.txt
内容:
123123
21321
2344
23432