• 技术文章 >Python技术 >Python基础教程

    python清洗文件数据的方法

    小妮浅浅小妮浅浅2021-08-19 09:31:15原创5491

    1、直接打开日志文件,往另外一个文件中按照要过滤的要求进行过滤。

    1

    2

    3

    4

    5

    6

    import io;

    with open('a.txt', 'w') as f:   

        for line in open('c:/201509.txt'):   

            if line.find('更改项目')>0 and line.find('500')>0: 

                f.write(line+"\n");

    print("输出完成");

    2、使用filter。

    1

    2

    3

    4

    5

    6

    7

    import io;

    def isData(s):

        return s.find('更改项目')>0 and s.find('500')>0;

    with open('a.txt', 'w') as f:            

           list1=list(filter(isData,open('c:/201509.txt')));   

           for (offset,item) in enumerate(list1):

                f.write(str(offset)+":"+item);

    3、对多个文件进行过滤,可以借助其名称的规律,遍历文件之后。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    import codecs

    with codecs.open('a.txt','a', encoding='utf_8_sig') as f:

        for i in range(205,210):

            f.write(str(i)+"\r\n");  

            print(str(i));

            for line in open('c:/20160907'+str(i)+'.log', encoding='utf_8_sig'):

                if line.find('url为')>=0 : 

                    print(line);

                    f.write(line+"\r\n");

    print("输出完成");

    以上就是python清洗文件数据的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python清洗
    上一篇:python在带参的函数中使用装饰器 下一篇:python旋转图片和压缩像素的方法

    相关文章推荐

    • 如何用Python编写客户端程序• Python中tail -f如何实现• python如何实现Stack• python类如何自定义实例化• python tqdm是什么• python异常处理的常见错误• python logging日志的禁用• python for循环遍历位置的查找• python if判断的使用格式• python break和continue的比较• python在带参的函数中使用装饰器

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网