第一行***处输入文件名
with open(file=r"***.cpp", mode="r", encoding="utf-8") as fb:
# 考虑第一行就是#等,txt初始化为 `\n`
txt = "\n"
while True:
# 循环读入行
line = fb.readline()
# 如果是空,则结束
if not line:
break
# 有 "//" ,舍去 "//" 后面的内容
if line.find("//") != -1:
line = line[: line.find("//")]
# 将line剔除前后的空格和换行
line = line.strip()
# 如果该行有'#',该行需要单独一行
if line.find("#") != -1:
# 如果txt已经有换行,则不需要再添,否则需要添加换行
if txt[-1] != '\n': txt += "\n"
line += "\n"
txt += line
# 输出到 压行.cpp 文件内
with open(file = r"压行.cpp", mode="w", encoding="utf-8") as f:
print(txt, file=f)
print("ok")
嘻嘻