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

yipeiwu_com6年前Python基础

一、问题描述

筛选出多个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文件中的数据进行筛选的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python+selenium实现163邮箱自动登陆的方法

python+selenium实现163邮箱自动登陆的方法

本文介绍了 让我们先来预览一下代码运行效果吧: 首先分析163邮箱登陆页面的网页结构(按F12或单击鼠标右键选择审查元素) 1、定位到登陆框(注意登录框是一个iframe,如果不定位...

SublimeText 2编译python出错的解决方法(The system cannot find the file specified)

[Error 2] The system cannot find the file specified 解决方法:1.环境变量path添加:C:\Python32\Tools\Scrip...

wxPython:python首选的GUI库实例分享

wxPython:python首选的GUI库实例分享

wxPython是Python语言的一套优秀的GUI图形库,允许Python程序员很方便的创建完整的、功能健全的GUI用户界面。 wxPython是作为优秀的跨平台GUI库wxWidge...

Python编程中的反模式实例分析

本文实例讲述了Python编程中的反模式。分享给大家供大家参考。具体分析如下: Python是时下最热门的编程语言之一了。简洁而富有表达力的语法,两三行代码往往就能解决十来行C代码才能解...

Python3.4 tkinter,PIL图片转换

Python3.4 tkinter,PIL图片转换

先给大家分享一下全部代码 import os from PIL import Image import tkinter import tkinter.filedialog impor...