skip to content
Liu Yang's Blog

脚本:递归合并代码文件到一个文本

/ 2 min read

Updated:

大二时写的一个小脚本,因为还算有用,特此留存:递归遍历目录,把 C++ / Python 源文件的内容连同文件名写进一个文本文件,适合整理代码或提交软著、课程材料。

import os
from pathlib import Path
# 要遍历的目录
workPath = "./work"
# 输出文件
totalSourceFile = open("d:\\source.txt", "a+", encoding="utf-8")
def getCodeSource(filesdir):
for filename in os.listdir(filesdir):
fileBasename = filename
# 合并文件名和路径
filename = os.path.join(filesdir, filename)
if Path(filename).is_dir():
# 目录:递归查找
getCodeSource(filename)
elif Path(filename).suffix in (".cpp", ".py", ".h"):
# 需要的代码文件:cpp / py / h
print(filename)
with open(filename, encoding="utf-8") as sourcefile:
totalSourceFile.write("\n文件名: " + fileBasename + "\n")
totalSourceFile.write(sourcefile.read())
getCodeSource(workPath)
totalSourceFile.close()

整理时顺手修了原脚本判断文件类型的两个问题:

  • 原来写的是 filename.find('.py'),没有和 > 0 比较。find 找不到时返回 -1,在 Python 里是真值,所以几乎所有文件都会被收进来。
  • 用 find('.h') 做子串匹配,.html 也会命中,只好再额外排除。

改成按后缀名(Path.suffix)判断后,这两个问题都没有了。