Python:使用递归文件夹读取和wri

2024-03-28 15:46:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

# cwd = "C:\Users\johnr\Desktop\myFolder" - current working directory
for filename in os.listdir(os.path.join(cwd, "content")):
    header_file = open(header_file_dir, "r")
    footer_file = open(footer_file_dir, "r")
    if ".md" in filename:
        newFilename = filename.replace(".md", ".html")
    if ".tile" in filename:
        newFilename = filename.replace(".tile", ".html")
    elif ".html" in filename:
        newFilename = filename
    elif ".txt" in filename:
        newFilename = filename.replace(".txt", ".html")
    else:
        print(filename+" is not a valid file type!")

    currents_working_file = open(os.path.join(cwd, "build", newFilename), "w")

    # Write the header
    currents_working_file.write(header_file.read())

    # Get the actual stuff we want to put on the page
    text_content = open(os.path.join(cwd, "content", filename), "r")
    if ".md" in filename:
        text_cont1 = "\n"+markdown.markdown(text_content.read())+"\n"
    elif ".tile" in filename:
        text_cont1 = "\n"+textile.textile(text_content.read())+"\n"
    elif ".html" in filename:
        text_cont1 = text_content.read()
    elif ".txt" in filename:
        text_cont1 = text_content.read()
    else:
        print(filename+" is not a valid file type!")

    # Write the text content into the content template and onto the build file
    content_templ_dir = os.path.join(cwd, "templates", "content_page.html")
    if os.path.exists(content_templ_dir):
        content_templ_file = open(content_templ_dir, "r")
        content_templ_file1 = content_templ_file.read()
        content_templ_file2 = content_templ_file1.replace("{page_content}", text_cont1)
        currents_working_file.write(content_templ_file2)
    else:
        currents_working_file.write(text_cont1)

    # Write the footer to the build file
    currents_working_file.write("\n"+footer_file.read())

    # Close the build file
    currents_working_file.close()

它在“content”目录中搜索一个文件,然后在“build”目录中创建一个同名文件。当“content”目录中的文件夹中有文件时,如何使此工作正常?你知道吗


Tags: thepathtextinreadoshtmltempl
2条回答

为了递归遍历目录,Python提供了^{}

for root, dirs, files in os.walk(os.path.join(cwd, "content")):
    relative_path = os.path.relpath(root, os.path.join(cwd, "content"))
    for filename in files:
        currents_working_file = open(os.path.join(cwd, "build", relative_path, filename), "w")

假设cwd只保存到当前工作目录的路径:

from pathlib import Path
from itertools import chain

source_extensions = {'md', 'html', 'txt'}
source_root_dir_path = Path("content")
source_file_paths = chain.from_iterable(
    source_root_dir_path.glob("**/*.{}".format(ext)) for ext in source_extensions
)
for p in source_file_paths:
    destination_file_path = Path("build", *p.with_suffix(".html").parts[1:])
    destination_file_path.parent.mkdir(parents=True, exist_ok=True)
    with destination_file_path.open('w') as f:
        f.write(header_file.read())
        f.write("\n")
        f.write(footer_file.read())

相关问题 更多 >