Hongmu Notes
Home Language Notes Combine multiple Python articles into a single article.
Language Notes python

Combine multiple Python articles into a single article.

Combine multiple Python articles into a single article.

A friend mentioned that they needed to combine several Markdown-format files or articles into a single document.

ad1a1b7183162134

The requirement is simple: merge multiple TXT files within a folder into a single document in sequential order.
Combined output format:
<h3>Document 1 – File Name</h3>
Document 1 – File Content
<h3>Document 2 – File Name<-/h3>
Document 2 – File Content
<h3>Document 3 – File Name</h3>
Document 3 – File Content
<h3>Document 4 – File Name</h3>
Document 4 – File Content

net effect:

ad1a1b7183162304

Code:

 隐藏内容:会员可查看
import os
import markdown

# 获取输入和输出文件夹路径,如果没有输入就使用默认路径
input_folder = input("请输入输入文件夹路径(默认为'./text'):") or './text'
output_folder = input("请输入输出文件夹路径(默认为'./Mytext'):") or './Mytext'

# 检查输入和输出文件夹是否存在,不存在则创建文件夹
os.makedirs(input_folder, exist_ok=True)
os.makedirs(output_folder, exist_ok=True)

# 获取Markdown文件名列表
md_file_list = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
md_file_list.sort()

# 每四篇文章进行合并
for i in range(0, len(md_file_list), 4):
    output_filename = md_file_list[i+3][:-4] + '.txt'
    output_path = os.path.join(output_folder, output_filename)

    output_list = []
    for md_filename in md_file_list[i:i+4]:
        with open(os.path.join(input_folder, md_filename), 'r', encoding='utf-8') as md_file:
            md_content = md_file.read()
            # 将Markdown格式转换为html格式
            html_content = markdown.markdown(md_content)
            title = md_filename[:-4]
            output_list.append((title, html_content))

    # 写入输出文件
    with open(output_path, 'w', encoding='utf-8') as output_file:
        for title, html_content in output_list:
            output_file.write(f"<h3>{title}</h3>\n{html_content}\n")

    # 输出详细信息
    print(f"合成第{i//4+1}篇文章:{output_filename},包含以下四篇文章:")
    for title, _ in output_list:
        print(title)

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

Import " requests" could not be resolved from source

Import " requests" could not be resolved from source Language Notes python

This error occurred when using Pylance, a Python language server. Among them, " Import " requests" could not be resolved from source" This error message indicates that the requests module is referenced in your code, but Pylance cannot find the location of the module from the source. The possible reason is that you don't have an …
👁 1771
Reinstall Python and requests libraries

Reinstall Python and requests libraries Language Notes python

If you meet " Import " requests" could not be resolved from source" You can try reinstalling Python and requests libraries. First, you need to uninstall the current Python and requests libraries. On Windows systems, you can use the command prompt …
👁 439
WARNING: Skipping requests as it is not installed.

WARNING: Skipping requests as it is not installed. Language Notes python

This error message indicates that your Python environment lacks the requests library, and this library is called in your code, so Python cannot execute your code normally. The solution to this problem is to install the requests library. You can use the pip command on the command line to install: pip install requests If you are using Python3, you can use the pip3 command …
👁 2100
Python reported an error. What is the reason? AttributeError: partially initialized module ' openai'  has no attribute ' Completion' (most likely due to a circular import)

Python reported an error. What is the reason? AttributeError: partially initialized module ' openai' has no attribute ' Completion' (most likely due to a circular import) Language Notes python

This error prompt indicates that there is a problem when importing the openai module and the specific Completion attribute, which is probably caused by circular import. The reason for this error may be that two or more modules in your code are imported from each other, forming a circular dependency. For example, module A imports module B, and module B imports module A.. Cyclic import will cause the module not to initialize correctly when loading, thus …
👁 656
How does python package and run on Windows?

How does python package and run on Windows? Language Notes python

The most common way to package and run Python programs on Windows is to use PyInstaller. PyInstaller is a free and cross-platform Python application packaging tool, which can package Python code and its dependent libraries into an independent executable file, making it possible to run Python programs on systems without Python interpreters installed. The following is to make …
👁 300
What programming software is good for python development?

What programming software is good for python development? Language Notes python

There are many programming softwares developed by Python. The following are some commonly used Python integrated development environments (IDE) and editors: PyCharmPyCharm is an integrated development environment developed by JetBrains, which is specially designed for Python developers. PyCharm is powerful and provides a series of advanced functions such as code completion, debugging, version control, code refactoring, etc., which can help developers improve their work …
👁 175

Recommended reading

Responsive Xiangzhou Livestock Farming Cooperative Website Template 0719

Responsive Xiangzhou Livestock Farming Cooperative Website Template 0719 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for Xiangzhu Livestock Breeding Cooperative. Its natural and professional design effectively showcases Xiangzhu pig farming operations, cooperative management, product supply chain, and breeding techniques. It helps livestock breeding cooperatives demonstrate their online presence and expand their sales channels. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 57
(Adaptive Mobile Version) Door & Window Industry Website Template – Download Windows Source Code for Door & Window Systems – 1136

(Adaptive Mobile Version) Door & Window Industry Website Template – Download Windows Source Code for Door & Window Systems – 1136 Practical Collection pbootcms Template

A PbootCMS website template for the door and window industry and system solutions, compatible with both PC and WAP devices. Featuring a modern, professional design style, it is ideal for showcasing door and window products, system solutions, and installation case studies. This template helps door and window brands showcase their products online and attract both residential and commercial clients. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn | Related Articles: Pb...
👁 37
(Adaptive mobile version) Blue Building Materials Panel PBootCMS Website Template; Acrylic Panel Website Source Code Download – 0404

(Adaptive mobile version) Blue Building Materials Panel PBootCMS Website Template; Acrylic Panel Website Source Code Download – 0404 Practical Collection pbootcms Template

An adaptive mobile-friendly website template for blue building materials panels and acrylic panels, powered by PbootCMS. The modern and professional design is ideal for showcasing panel products, custom manufacturing services, and project cases. It enables building materials companies to display their products online and attract clients from the renovation and advertising industries. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 45
Mysql efficiency improvement: limit this piece of shit

Mysql efficiency improvement: limit this piece of shit Language Notes mySql

In mysql, the efficiency of limit is not high, especially my millions of data, limit 100000, 50, so writing, the query is even slower, at first it was quite fast, and the server cup behind it was directly filled for me! I thought the server was hacked, so I looked for the problem. I looked for it for a few days, but it turned out to be this dog, which made me angry! So I inquired about the principle of limit, emmm, change! Must be changed ...
👁 155
Responsive potted plant and floral website template – 0720

Responsive potted plant and floral website template – 0720 Practical Collection Yiyou template

An eYouCMS responsive website template designed for the greenery, floral, and potted plant industries. Its fresh and natural design style is ideal for showcasing plant and floral products, potted plant designs, brand stories, and gardening services. This template helps floral and greenery brands effectively present their products online and attract both residential and corporate customers. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Common Questions About eYouCMS Installation...
👁 51
(PC+WAP) Agricultural Irrigation Equipment Website Template – Agricultural Machinery Equipment Website Source Code Download – 1137

(PC+WAP) Agricultural Irrigation Equipment Website Template – Agricultural Machinery Equipment Website Source Code Download – 1137 Practical Collection pbootcms Template

An agricultural irrigation and farm machinery equipment PbootCMS website template, compatible with both PC and WAP devices. The natural and professional design is ideal for showcasing agricultural irrigation products, farm machinery equipment, and field applications. It helps farm machinery companies showcase their products online and attract agricultural customers. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn | Related Articles...
👁 52