最近在新入职的公司中,组里有很多人都在使用Python进行开发,自己也试着学习和整理了一下平时经常会使用到的工具类,其中有很多也是借鉴了网上的很多帖子,供大家参考。
需要注意的是:在文件处理的各种问题中,别忘记的一点就是对字符集的指定,否则会出现字符集相关的bug。
1. txt转换成csv
target = open(r"test.csv","a") #最终写入的csv文件的绝对路径
with open(r"test.txt",'r') as lines : #读取的txt文件的绝对路径
for line in lines :
# print(type(line))
newline = line.replace("&",",") # 指定txt文件每行中多个字段的分隔符,将其替换成,
target.write(newline)
target.close()
2. txt转换成Excel
方式一:
import os
import xlwt
import datetime
import re
def create_and_write_data_to_excel(p_file_name_prefix=None, p_sheetname=None, p_data=None):
try:
wbk = xlwt.Workbook()
if p_sheetname is None:
p_sheetname = 'Sheet1'
sheet = wbk.add_sheet(p_sheetname, cell_overwrite_ok=True)
for i in range(len(p_data)):
for j in range(len(p_data[i])):
sheet.write(i, j, p_data[i][j])
filename = p_file_name_prefix + datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".xls"
wbk.save(filename)
return wbk
except:
print("------")
pass
if __name__ == '__main__':
# module_path = os.path.dirname(__file__)
# filename = module_path + '/report_db_20180301_20180302_11881.2_0_100_gdt.txt'
filename = r"D:\DevSoftware\IDEA\IntelliJ IDEA 2019.1.3\workspace\JIGUANG-PYTHON\com\jiguang\python\utils\表一.txt"
"""
txt 内容
gdt 20180301 -1.0000 6 2 0.3333 -0.1667 -0.5000
gdt 20180302 -1.0000 4 1 0.2500 -0.2500 -1.0000
gdt SUM 11881.2000 10 3 0.3000 1188.1200 3960.4000