本文主要是介绍零代码编程:用kimichat批量重命名markdown文件并合并,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一个文件夹里面有很多个markdown文件,需要全部合并成一个txt文件:
可以在kimichat输入框中输入提示词:
你是一个Python编程专家,要完成一个编写Python脚本的任务,具体步骤如下:
打开文件夹:D:\prompts-for-edu-main\prompts-for-edu-main
获取文件夹里面所有以md为后缀的文件;
将所有这些md文件重命名为txt文件,比如:Tutor.MD重命名为Tutor.txt;
将所有txt文件合并为一个txt文件,文件标题名为:edup.txt
注意:
每一个步骤都要打印出信息;
使用原始字符串 r"path" 来避免转义问题;
在重命名操作中添加异常处理来捕获和报告错误;
将任务分解为多个函数,每个函数执行一个特定的任务;
Kimichat生成Python脚本代码:
import os
import glob
# 打开并显示指定文件夹路径
def open_folder(folder_path):
print(f"Opening folder: {folder_path}")
if not os.path.exists(folder_path):
print(f"The folder '{folder_path}' does not exist.")
else:
print(f"Successfully accessed the folder: {folder_path}")
# 获取文件夹中所有.md文件并打印
def get_md_files(folder_path):
md_files = glob.glob(os.path.join(folder_path, "*.md"))
print(f"Found {len(md_files)} .md files:")
for file in md_files:
print(file)
return md_files
# 将.md文件重命名为.txt文件,并打印信息和异常处理
def rename_md_to_txt(md_files):
for md_file in md_files:
try:
base_name, ext = os.path.splitext(md_file)
txt_filename = base_name + ".txt"
os.rename(md_file, txt_filename)
print(f"Renamed {md_file} to {txt_filename}")
except Exception as e:
print(f"An error occurred while renaming {md_file}: {e}")
# 合并所有.txt文件到一个edup.txt文件,并打印信息
def merge_txt_files(folder_path, output_file_name):
with open(output_file_name, "w", encoding='utf-8') as outfile:
txt_files = glob.glob(os.path.join(folder_path, "*.txt"))
for txt_file in txt_files:
with open(txt_file, "r", encoding='utf-8') as infile:
content = infile.read()
outfile.write(content)
outfile.write("\n\n") # 添加分隔符
print(f"File {txt_file} has been merged into {output_file_name}")
print(f"All .txt files have been successfully merged into {output_file_name}")
# 主程序
if __name__ == "__main__":
folder_path = r"D:\prompts-for-edu-main\prompts-for-edu-main"
output_file_name = "edup.txt"
open_folder(folder_path)
md_files = get_md_files(folder_path)
if md_files:
rename_md_to_txt(md_files)
merge_txt_files(folder_path, output_file_name)
else:
print("No .md files found in the folder.")
程序运行,成功重命名、合并:
这篇关于零代码编程:用kimichat批量重命名markdown文件并合并的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!