python处理txt文件常用方法

时间:2022-07-23
本文章向大家介绍python处理txt文件常用方法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
分享切割txt文件、合并txt文件、excel转txt方法
"""
 * Create by dell on 2020/23
 * Author :wencheng
 * 微信公众 :自动化测试 To share

"""
import os
import os.path


def spilt_file():
    limit = 1000000  # 切割后单个文件的最大行数
    file_count = 0
    line_list = []
    # 打开需要切割的文件
    with open(r'testlog.txt', 'r', errors='ignore') as f:
        for line in f:  # 读取每一行
            line_list.append(line)  # 把每一行数据分别加入到line_list列表里面
            if len(line_list) < limit:  # 如果line_list列表的长度‘小’于指定的切割后单个文件的最大行数
                continue
            file_name = './data/log' + str(file_count) + '.txt'  # 如果line_list列表的长度‘等’于指定的切割后单个文件的最大行数
            with open(file_name, 'w') as file:  # 写入文件
                for new_line in line_list[:-1]:
                    file.write(new_line)
                file.write(line_list[-1].strip())
                line_list = []
                file_count += 1
    if line_list:  # 文件读取完后,如果line_list列表里仍有数据未保存,就把数据写入一个文件
        file_name = './data/log' + str(file_count) + '.txt'
        with open(file_name, 'w') as file:
            for line in line_list:
                file.write(line)

    print('done')


def MergeTxt(filepath, outfile):
    k = open(filepath + outfile, 'a+')
    for parent, dirnames, filenames in os.walk(filepath):
        for filepath in filenames:
            txtPath = os.path.join(parent, filepath)  # txtpath就是所有文件夹的路径
            f = open(txtPath)
            ##########换行写入##################
            # k.write(f.read()+"n")
            k.write(f.read())
    k.close()
    print("finished")


import xlwt  # 需要的模块


def txt_xls(filename, xlsname):
    """
    :文本转换成xls的函数
    :param filename txt文本文件名称、
    :param xlsname 表示转换后的excel文件名
    """
    try:
        f = open(filename, encoding="utf-8")
        xls = xlwt.Workbook()
        # 生成excel的方法,声明excel
        sheet = xls.add_sheet('sheet1', cell_overwrite_ok=True)
        x = 0
        while True:
            # 按行循环,读取文本文件
            line = f.readline()
            if not line:
                break  # 如果没有内容,则退出循环
            for i in range(len(line.split('t'))):
                item = line.split('t')[i]
                items = item.split(":")
                print(items[1])
                sheet.write(x, i, items[0])  # x单元格经度,i 单元格纬度
            x += 1  # excel另起一行
        f.close()
        xls.save(xlsname)  # 保存xls文件
    except:
        raise

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家的支持。