请选择 进入手机版 | 继续访问电脑版
设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
楼主: crossin先生

【每日一坑 6】 查找文件内容

[复制链接]

0

主题

0

好友

30

积分

新手上路

Rank: 1

发表于 2017-3-27 22:53:45 |显示全部楼层
  1. #! /usr/bin/env python
  2. #coding=utf-8
  3. import os
  4. rootdir = 'E:\Famine' #定义根目录

  5. #三个参数:分别返回1.父目录 2.父目录下所有文件夹名字(不含路径) 3.父目录下所有文件名字
  6. for father_path, foldernames, filenames in os.walk(rootdir):
  7.    
  8.     for filename in filenames: #遍历文件

  9.         if os.path.splitext(filename)[1] == '.txt': #判断文件后缀是否是txt
  10.             dir = os.path.join(father_path, filename) #组合文件路径
  11.             
  12.             if os.path.exists(dir): #判断文件路径是否存在
  13.                 folder = os.path.split(os.path.split(dir)[0])[1] #获取文件上层文件夹
  14.                 print 'The upper folder is:\n%s' % folder, '\n'
  15.                 print 'The file name is:\n%s' % filename, '\n'
  16.                
  17.                 f = file(dir) #打开文件
  18.                 context = f.read() #读取文件内容
  19.                 print 'The contents of this file is', '\n', context, '\n\n'
  20.                 f.close() #关闭文件
复制代码
回复

使用道具 举报

0

主题

1

好友

61

积分

注册会员

Rank: 2

发表于 2017-4-11 15:33:46 |显示全部楼层
crossin先生 发表于 2016-2-16 22:35
查找文件里的内容不用readlines,直接read到一个字符串,然后find就可以了。
另外你这个代码好像无法检测 ...

谢谢你,crossin先生,我在你的论坛上学习了python之后,就找了一个写python的工作,所以到现在才来看,特意来感谢你的。谢谢!
回复

使用道具 举报

174

主题

45

好友

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

发表于 2017-4-11 23:29:28 |显示全部楼层
xqqxjnt1988 发表于 2017-4-11 15:33
谢谢你,crossin先生,我在你的论坛上学习了python之后,就找了一个写python的工作,所以到现在才来看, ...

#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

1

主题

0

好友

39

积分

新手上路

Rank: 1

发表于 2017-8-31 11:57:51 |显示全部楼层

import fnmatch
import os


def filterFile(filePath, contain):
    for grandFather, father, sons in os.walk(filePath):
        sonList = []
        for son in sons:
            sonList.append(son)
        fnmatchs = fnmatch.filter(sonList, "*.txt")
        if len(fnmatchs) != 0:
            for fnmatchFile in fnmatchs:
                absultePath = grandFather + "/" + fnmatchFile
                absultePath = absultePath.replace("\\", "/")
                f = file(absultePath)
                str = f.read()
                f.close()
                if str.__contains__(contain):
                    print absultePath


path = raw_input("请输入遍历的绝对路径:")
filterFile(path, "aaa")

做的过程中存在两个问题困扰了我:
1、sonList刚开始在方法外放着,导致生命周期太长,所以导致了我的拼接出来的路径下不存在某个文件
2、拼接出来的路径是双引号的,用来打开文件会出错。但是我敲的demo在pycharm中打印出来却是单斜杠的。一直不知道是哪里出问题了。最后发现是pycharm自动将其转化为合格的路劲。
回复

使用道具 举报

0

主题

2

好友

46

积分

新手上路

Rank: 1

发表于 2018-5-16 16:48:56 |显示全部楼层
我这边自己建了一个文件夹,里面放了一个子文件夹,一些txt、excel和word文件。
运行代码后,txt文件正常显示内容,excel和word都不正常。
自己搜索了下,说是excel和word的读取要用其他模块来处理的,但是基础课程中讲到read的使用时,老师好像也没有提到txt文件之外的类型该怎么读取,麻烦问下老师excel这些是要再另外处理吗?
1526460289(1).jpg
1526460267(1).jpg
回复

使用道具 举报

174

主题

45

好友

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

发表于 2018-5-17 22:42:57 |显示全部楼层
coolqing 发表于 2018-5-16 16:48
我这边自己建了一个文件夹,里面放了一个子文件夹,一些txt、excel和word文件。
运行代码后,txt文件正常显 ...

excel、word是不能直接读取的,要读写的话,需要用专门的库
公众号回复 excel 有介绍
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

0

主题

0

好友

10

积分

新手上路

Rank: 1

发表于 2018-8-23 11:46:19 |显示全部楼层
crossin先生 发表于 2014-1-2 10:30
open只是在python打开,把内容读入内存,不会调用任何其他程序打开。但这个过程是很慢的。所以虽然可以实 ...

import os
import re
dirnme = 'E:\Study during Graduate school'
list_dir = []
for dirnow,folds,files in os.walk(dirnme):
    # print(dirnow)
    # print(folds)
    # print(files)
    for fs in files:
        # print(fs)
        filtext = re.findall('.txt',fs)
        if filtext:
            list_dir.append(os.path.join(dirnow, fs))
    # filtext = re.findall("*.txt",files)
    # list_dir.append(''.join(dirnow,files))
print(list_dir)
回复

使用道具 举报

0

主题

0

好友

52

积分

注册会员

Rank: 2

发表于 2020-10-14 23:22:50 |显示全部楼层
  1. import os
  2. import chardet

  3. def match(search_path,match_text):
  4.     result_list = []

  5.     for root, dirs, files in os.walk(search_path):
  6.         # 遍历所有的文件
  7.         for file in files:
  8.             # 判断文件名是否以“.txt”结尾
  9.             if file.endswith(".txt"):

  10.                 # 获取文件的绝对路径
  11.                 file_path = os.path.join(root,file)
  12.                 # print(file_path)

  13.                 # 判断文件的编码格式
  14.                 with open(file_path, "rb") as obj1:
  15.                     text_b = obj1.read()
  16.                     text_encoding = chardet.detect(text_b)["encoding"]
  17.                     # print(text_encoding)

  18.                 # 用指定的编码格式打开文件,判断文本参数是否存在于文件内容
  19.                 with open(file_path, "r", encoding=text_encoding) as obj2:
  20.                     text = obj2.read()
  21.                     if match_text in text:
  22.                         result_list.append(file_path)

  23.     return result_list


  24. if __name__ == "__main__":

  25.     # 提示用户输入路径
  26.     while True:
  27.         search_path = input("请输入搜索路径: ").strip()
  28.         # 判断路径是否存在
  29.         if os.path.exists(search_path):
  30.             break
  31.         print("路径不存在!")
  32.     # 提示用户输入匹配的文字
  33.     match_text = input("请输入匹配的文字: ")
  34.     file_list = match(search_path,match_text)
  35.     # 展示匹配到的文件
  36.     print("匹配到的文件如下: ")
  37.     for one in file_list:
  38.         print(one)
复制代码
result.png
回复

使用道具 举报

174

主题

45

好友

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

发表于 2020-10-15 13:02:59 |显示全部楼层
jodie 发表于 2020-10-14 23:22

实际运用中,因为文件夹下可能有很多非文本文件,所以最好加上异常处理,避免报错跳出
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

3

主题

1

好友

111

积分

注册会员

Rank: 2

发表于 2021-2-13 19:24:08 |显示全部楼层
老师好,能看看嘛?望得到您的建议。

这个程序有些问题。比如我在文件夹中加上一个Word文件,它就会报错。大概是这样:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x82 in position 89: illegal multibyte sequence
老师能解释一下和提供个解决方法吗?谢谢啦!
  1. import os

  2. text = input('输入要检索的内容:\n')
  3. way = input('输入要检索的文件夹位置:\n')
  4. result = []

  5. for root, dirs, files in os.walk(way):
  6.     for f in files:
  7.         file_con = open(root + '\\' + f,encoding = 'utf-8').read()
  8.         if text in file_con:
  9.             result.append(f)
  10. print(result)
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-3-28 18:07 , Processed in 0.019652 second(s), 23 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部