连接 2 个具有不同文件扩展名的文件

Concatenate 2 files with different files extension

apple.yml
apple.md
orange.yml
orange.md

我有 .md 和 .yml 文件,如果文件名匹配,我想将它们合并成一个 .md 文件

这里的下一步是什么?

contents = {}
file_extension1 = "yml"
file_extension2 = "md"

# Get all files and directories that are in current working directory
for file_name in os.listdir('folder/'):
#     print(file_name)

    # Use '.' so it doesn't match directories
    if file_name.endswith(('.' + file_extension1 , '.'+ file_extension2)):
        print(file_name)

以下是 glob 模块的使用方法:

from glob import glob

for f1 in glob("*.yml"): # For every yml file in the current folder
    for f2 in glob("*.md"): # For every md file in the current folder
        if f1.rsplit('.')[0] == f2.rsplit('.')[0]: # If the names match
            with open(f1, 'r') as r1, open(f2, 'r') as r2: # Open each file in read mode
                with open(f"{new}_f2", 'w') as w: # Create a new md file
                    w.write(r1.read()) # Write the contents of the yml file into it
                    w.write('\n') # Add a newline
                    w.write(r2.read()) # Write the contents of the md file into it



该代码适用于 ymlmd 文件不一致的情况。如果所有 yml 文件都有相应的 md 文件,并且它们与其他干扰 ymlmd 文件位于一个文件夹中,您可以:

from glob import glob

m = sorted(glob("*.md"))
y = sorted(glob("*.yml"))

for f1, f2 in zip(m, y):
    with open(f1, 'r') as r1, open(f2, 'r') as r2:
        with open(f"new_{f1}", 'w') as w:
            w.write(f1.read())
            w.write('\n')
            w.write(f2.read())


更新:

解决以下评论:

from os import listdir

files = listdir()
for f in files: # For every yml file in the current folder
    if f.endswith('.yml') and f.rsplit('.')[1]+'.md' in files:
        with open(f1, 'r') as r1, open(f.rsplit('.')[1]+'.md', 'r') as r2: # Open each file in read mode
            with open(f"{new}_f2", 'w') as w: # Create a new md file
                w.write(r1.read()) # Write the contents of the yml file into it
                w.write('\n') # Add a newline
                w.write(r2.read()) # Write the contents of the md file into it