2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > Python-将txt文件转换成Excel

Python-将txt文件转换成Excel

时间:2019-04-21 03:12:23

相关推荐

Python-将txt文件转换成Excel

Excel 生成

import osimport xlwtclass TxtToExcel(object):def __init__(self, file_path):"""初始化excel:param file_path:文件存放目录路径"""self.file_path = file_pathself.workbook = xlwt.Workbook(encoding='utf-8')self.worksheet = self.workbook.add_sheet('My Worksheet', cell_overwrite_ok=True)self.style = xlwt.XFStyle() # 初始化样式self.font = xlwt.Font() # 为样式创建字体self.font.name = 'Times New Roman'self.font.bold = True # 黑体self.font.underline = True # 下划线# self.font.italic = True # 斜体字self.style.font = self.font # 设定样式self.header = [u'主机名', u'日期', u'时间', u'状态']def file_list(self, file):"""获取目录下的所有文件:return:"""return os.listdir(file)def get_file_path(self):"""获取文件路径:return:"""file_list = self.file_list(self.file_path)file_path_list = []for file in file_list:path = os.path.join(self.file_path, file)if os.path.isdir(path):file_path_list.extend([os.path.join(path, f) for f in self.file_list(path)])else:file_path_list.append(path)return file_path_listdef read_file_content(self, file):"""读取文件内容:return:"""with open(file, 'r', encoding='utf-8') as f:content = f.readlines()return content# return list(lines for lines in open(file, 'r', encoding='utf-8'))def writ_to_excel(self, row, content, file_name):"""写入excel文件:return:"""content_list = content.split(" ")while '' in content_list:content_list.remove('')i = 0for each_header in self.header:self.worksheet.write(0, i, each_header, self.style)i += 1content_list[0] = file_nameif len(content_list) <= 3:return Falseprint(content_list)for con in content_list[:3]:index = content_list.index(con)self.worksheet.write(row, index, con)self.worksheet.write(row, 3, '关闭')return Truedef get_file_content(self):"""获取txt文件内容并写入excel:return:"""files = self.get_file_path()files.remove(os.path.join(self.file_path, '转excel小工具.exe'))# 生成器方式获取文件内容generator_ex = (self.read_file_content(file) for file in files)index = 0for content in generator_ex:file_name = content.pop(0)for con in content:res = self.writ_to_excel(index+1, con, file_name)if res:index += 1else:index = indexself.workbook.save('../formatting.xls')if __name__ == '__main__':# path = r"D:\工作日志\txt转excel工具\trust"path = os.getcwd()import threadingtry:TxtToExcel(path).get_file_content()# 多线程t1 = threading.Thread(target=TxtToExcel(path).get_file_content, args=())t1.start()except Exception as e:print(e)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。