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

Python 连接2个具有不同文件扩展名的文件,python,yaml,markdown,re,listdir,Python,Yaml,Markdown,Re,Listdir,我有.md和.yml两个文件,如果文件名匹配,我想把它们合并成一个.md文件 下一步是什么 apple.yml apple.md orange.yml orange.md 以下是如何使用glob模块: contents = {} file_extension1 = "yml" file_extension2 = "md" # Get all files and directories that are in current working direct

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

下一步是什么

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

以下是如何使用
glob
模块:

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)



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

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


更新:

针对以下评论:

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

你不需要同时考虑这两种模式。对于每个*.yml文件,您可以直接检查对应的*.md文件是否存在。由于您处于联机状态,您可以解释如何将新的{new}f2移动到新文件夹将
打开时(f{new}f2,'w')更改为w:
打开时(f“C:/Users/User/Desktop/Folder/{new}f2,'w')更改为w:<代码>'C:/Users/User/Desktop/Folder/'是文件夹路径。
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