繁体   English   中英

Python - 将多个文件的内容复制到一个

[英]Python - copying the contents of several files to one

我需要帮助。 我在目录中有一些文件:

9000_1.txt
9000_2.txt
7000_1.txt
7000_2.txt
7000_3.txt

我想根据以下内容保存文件的内容:

9000.txt as sum files 9000_1.txt and 9000_2.txt
7000.txt as sum files 7000_1.txt and 7000_2.txt and 7000_3.txt
and ect

现在我现在有:

import os
import re

folderPath = r'C:/Users/a/Desktop/OD'

if os.path.exists(folderPath):
    files = []
    for name in os.listdir(folderPath):
        if os.path.isfile(os.path.join(folderPath, name)):
            files.append(os.path.join(folderPath, name))
    print(files)

    for ii in files:
        current = os.path.basename(ii).split("_")[0]

任何人都可以就此向 go 提供简单的建议吗?

当然 - 使用glob.glob方便地找到所有匹配的文件和我们的好朋友collections.defaultdict将文件分组,并循环遍历这些组:

import glob
import os
import shutil
from collections import defaultdict


folder_path = os.path.expanduser("~/Desktop/OD")

# Gather files into groups
groups = defaultdict(set)

for filename in glob.glob(os.path.join(folder_path, "*.txt")):
    # Since `filename` will also contain the path segment,
    # we'll need `basename` to just take the filename,
    # and then we split it by the underscore and take the first part.
    prefix = os.path.basename(filename).split("_")[0]

    # Defaultdict takes care of "hydrating" sets, so we can just
    groups[prefix].add(filename)

# Process each group, in sorted order for sanity's sake.
for group_name, filenames in sorted(groups.items()):
    # Concoct a destination name based on the group name.
    dest_name = os.path.join(folder_path, f"{group_name}.joined")
    with open(dest_name, "wb") as outf:
        # Similarly, sort the filenames here so we always get the
        # same result.
        for filename in sorted(filenames):
            print(f"Adding {filename} to {dest_name}")
            with open(filename, "rb") as inf:
                # You might want to do something else such as
                # write line-by-line, but this will do a straight up
                # merge in sorted order.
                shutil.copyfileobj(inf, outf)

这输出

Adding C:\Users\X/Desktop/OD\7000_1.txt to C:\Users\X/Desktop/OD\7000.joined
Adding C:\Users\X/Desktop/OD\7000_2.txt to C:\Users\X/Desktop/OD\7000.joined
Adding C:\Users\X/Desktop/OD\7000_3.txt to C:\Users\X/Desktop/OD\7000.joined
===
Adding C:\Users\X/Desktop/OD\9000_1.txt to C:\Users\X/Desktop/OD\9000.joined
Adding C:\Users\X/Desktop/OD\9000_2.txt to C:\Users\X/Desktop/OD\9000.joined

暂无
暂无

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

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