python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python对多个txt文件中的数据进行筛选

使用python对多个txt文件中的数据进行筛选的方法

作者:heavenmark

今天小编就为大家分享一篇使用python对多个txt文件中的数据进行筛选的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

一、问题描述

筛选出多个txt文件中需要的数据

二、数据准备

这是我自己建立的要处理的文件,里面是随意写的一些数字和字母

三、程序编写

import os

def eachFile(filepath):        
  pathDir =os.listdir(filepath)    #遍历文件夹中的text
  return pathDir

def readfile(name):          
  fopen=open(name,'r')
  for lines in fopen.readlines():     #按行读取text中的内容
    lines = lines.replace("\n", "").split(",")
    if 'aaa' in str(lines) and '2' not in str(lines): 
    #筛选出含有'aaa'并且不含数字2的每一行 
      print(lines)
  fopen.close()

filePath = "C:\\Users\\Administrator\\Desktop\\123"
pathDir=eachFile(filePath)
for allDir in pathDir:
  # child = os.path.join('%s%s' % (filepath, allDir))
  child = "C:\\Users\\Administrator\\Desktop\\123" + '\\' + allDir
  readfile(child)

以上只是利用if条件句对数据进行简单的筛选,可以用正则表达式做更复杂的数据筛选。

这篇使用python对多个txt文件中的数据进行筛选的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文