Python:使用递归文件夹进行读写

时间:2016-12-19 20:22:50

标签: 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()

搜索'内容'中的文件目录,然后在' build'中创建一个同名文件。目录。如果“内容”中的文件夹中有文件,我该如何才能完成这项工作? ?目录

2 个答案:

答案 0 :(得分:0)

为了递归遍历目录,Python提供了os.walk

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

答案 1 :(得分:0)

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