繁体   English   中英

将多个文件的数据连接到一个文件中并重命名该文件?

[英]Concatenate multiple files' data into one file and also rename the file?

使用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()

这是组合文本文件的另一种方法。

#! 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()

这是一个工作解决方案,它将文件名和文件内容存储在一个列表中,然后加入列表文件名并创建一个“组合”文件名,然后将所有文件的内容添加到它,因为列表附加的顺序是数据是读取这个就足够了(我的示例文件名是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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM