Python 多文件合并与空行删除
标题遇到的问题一将多个文件中的内容合并到一个文件中去。解决办法复制粘贴稍嫌麻烦。因此写了一段代码如下python python import os def re(file, filepath, wriefile): path file \\ filepath print(path) content open(path, rb) filecontent content.read() content.close() writefile open(wfile, a) writefile.write(// filepath \n) writefile.close() writefile open(wfile, ab) writefile.write(filecontent) writefile.close() # 原文件所在的位置 file rC:\classroom_system # 合并到的新的文件 wfile 123.txt for filepath in os.listdir(file): print(filepath) if php in filepath: # print(filepath) re(file, filepath, wfile) # print(filecontent)执行以上代码。可将文件夹中的所有文件的内容全部复制到123.txt中。但又遇到了第二个问题。问题二文件中有好多空行我需要将其删除。解决办法又写了一段代码。# 删除空行# 输入文件路径改成你自己的文件input_file123.txt# 输出文件路径处理后保存的新文件output_fileoutput.txt# 以二进制模式读取文件withopen(input_file,rb)asf:linesf.readlines()# 过滤只保留 不是 \n 的行filtered_lines[lineforlineinlinesifline!\n]# 把处理后的数据写入新文件withopen(output_file,wb)asf:f.writelines(filtered_lines)print(f处理完成已删除所有空行)print(f原文件{input_file})print(f新文件{output_file})运行此段代码OK搞定