背景介绍
有些场景下需要将系统的所有源码拷贝在一起,比如:申请软件著作权时需要提供源码,一个一个java文件copy就太慢了。
解决方案
利用python脚本读取并写入到txt
然后将txt复制到word即可
说明:
txt文件名默认为目录名,也是java项目工程名称
代码:
# coding=utf-8
import os
# import docx
class getCode:
list_name = []
# 查找path下所有java文件,reture list
@classmethod
def get_jsonfile(cls, path, file_list):
dir_list = os.listdir(path)
for x in dir_list:
new_x = os.path.join(path, x)
if os.path.isdir(new_x):
cls.get_jsonfile(new_x, file_list)
else:
file_tuple = os.path.splitext(new_x)
if file_tuple[1] == '.java':
file_list.append(new_x)
return file_list
@classmethod
def write_txt(cls, write_path):
if not os.path.exists(write_path):
os.makedirs(write_path)
# 循环读取文件路径
for i in cls.list_name:
for k,v in i.items():
file_list = []
cls.get_jsonfile(v, file_list)
# 保存到文件
with open(f'{write_path}\\{k}.txt', "w", encoding='UTF-8') as write_file:
for json_file in file_list:
with open(json_file, "r", encoding='UTF-8')as read_file:
write_file.write(read_file.read())
@classmethod
def getListDir(cls, read_path, write_path):
# 查找 path下所有文件或目录名称到list
dirs = os.listdir(read_path)
for dir in dirs:
# 拼接路径,获取文件路径
path_1 = os.path.join(os.path.abspath(read_path), dir)
cls.list_name.append({dir:path_1})
cls.write_txt(write_path)
@classmethod
def start(cls, read_path, write_path):
cls.getListDir(read_path, write_path)
if __name__ == '__main__':
# 源代码路径
read_path = 'C:\\Users\\qaq\Desktop\\aaa'
# 读取后txt的保存路径
write_path = 'C:\\Users\\qaq\Desktop\\bbb'
getCode.start(read_path,write_path)