用python实现文件查找的简单介绍

本文目录一览:

如何用python查询文件路劲

最近在用Python脚本处理文件夹下面的文件名的搜索和重命名。其中碰到如何递归遍历文件夹下面所有的文件,找到需要的文件,并且重命名的问题。其实如果看看Python的document,还是比较简单的,这里直接给出使用方法,免得大家还要花精力去查找。

环境:

文件夹结构:

—-path1

—-path1-1

—-path1-1.1.txt

—-path1-2

—-path1.1.txt

—-path2

—-recursiveDir.py

文件夹结构如上所示。

代码分析(recursiveDir.py):

[python] view plaincopy

span style=”font-size:18px;”import os

””’

本脚本用来演示如何遍历py脚本所在文件夹下面所有的文件(包括子文件夹以及其中包含的文件)。

重点演示如何获取每个文件的绝对路径。注意os.path.join(dirpath, filename)的用法。

”’

rootdir = os.getcwd()

print(‘rootdir = ‘ + rootdir)

for (dirpath, dirnames, filenames) in os.walk(rootdir):

#print(‘dirpath = ‘ + dirpath)

for dirname in dirnames:

print(‘dirname = ‘ + dirname)

for filename in filenames:

#下面的打印结果类似为:D:\pythonDirDemo\path1\path1-1\path1-1.1.txt

print(os.path.join(dirpath, filename))

if(filename==’path1-1.1.txt’):

os.chdir(dirpath)

#os.rename(os.path.join(dirpath, filename), dirpath + os.sep + ‘path1-1.1.new.txt’)

os.rename(‘path1-1.1.txt’, ‘path1-1.1.new.txt’)

#os.remove(os.path.join(dirpath, filename))

#下面的输出为fileName = path1-1.1.txt,并未包含绝对路径,所以需要使用os.path.join来链接,获取绝对路径

print(‘fileName = ‘ + filename)

print(‘——————one circle end——————-‘)/span

所以可以看到程序中使用os.path.join(dirpath, filename)来拼接出绝对路径出来。注意下面的重命名用法,可以将工作目录切换到os.chdir(dirpath),这样就可以直接用os.rename(oldfile, newfile).Python会自动到dirpath下面查找oldfile并且重命名为newfile。注意工作目录的含义:在Python的GUI中,使用os.getcwd()可以获取到当前工作目录。测试如下:

[html] view plaincopy

span style=”font-size:18px;” os.chdir(‘D:’)

os.getcwd()

‘D:\\pythonDirDemo\\path1\\path1-1’

os.chdir(‘D:\\’)

os.getcwd()

‘D:\\’/span

可见却是可以用chdir改变工作目录。这个代码只是在重命名的时候用到的小技巧而已,大家知道有这个东西就行了,不过调用chdir之后,后续再获取getcwd()就会被影响,所以警惕。

如何用Python实现在文件夹下查找一个关键词

#!/usr/bin/python

#coding:utf8

import os

#判断文件中是否包含关键字,是则将文件路径打印出来

def is_file_contain_word(file_list, query_word):

for _file in file_list:

if query_word in open(_file).read():

print _file

print(“Finish searching.”)

#返回指定目录的所有文件(包含子目录的文件)

def get_all_file(floder_path):

file_list = []

if floder_path is None:

raise Exception(“floder_path is None”)

for dirpath, dirnames, filenames in os.walk(floder_path):

for name in filenames:

file_list.append(dirpath + ‘\\’ + name)

return file_list

query_word = raw_input(“Please input the key word that you want to search:”)

basedir = raw_input(“Please input the directory:”)

is_file_contain_word(get_all_file(basedir), query_word)

raw_input(“Press Enter to quit.”)

请采纳

python从文件中查找数据并输出

#注意,这里的代码用单空格缩进

import re

#写上你的文件夹路径

yourdir=””

keywordA = “keywordA”

keywordB = “keywordA(\d+)”

files = [os.path.join(yourdir,f) for f in os.listdir(yourdir)]

with open(“out.txt”,”w”) as fo:

 for f in files:

  fname = os.path.basename(f)

  with open(f,”r”) as fi:

   for line in fi:

    if line.strip():

     searchA = re.search(keywordA,line.strip())

     if searchA:

      searchB = re.search(keywordB,line.strip())

      if searchB:

       print(fname,serachB.groups()[0],sep=”\t”,file=fo)

如何用Python语言实现在一个文件中查找特定的字符串?

用正则表达式

 s=’hello world’

 import re

 re.search(‘wor’,s)

_sre.SRE_Match object; span=(6, 9), match=’wor’

请问如何用python实现查找指定文件?

若不包含子目录的遍历:

import glob

for filename in glob.glob(“f:/py/*.exe”):

    print filename

否则可以:

import os

import fnmatch

def iterfindfiles(path, fnexp):

    for root, dirs, files in os.walk(path):

        for filename in fnmatch.filter(files, fnexp):

            yield os.path.join(root, filename)

for filename in iterfindfiles(r”f:/py”, “*.exe”):

    print filename

用python实现一个本地文件搜索功能。

import re,os

import sys

def filelist(path,r,f):

“””

function to find the directions and files in the given direction

according to your parameters,fileonly or not,recursively find or not.

“””

file_list = []

os.chdir(path)

filename = os.listdir(path)

if len(filename) == 0:

os.chdir(os.pardir)

return filename

if r == 1: ##

if f == 0: # r = 1, recursively find directions and files. r = 0 otherwise.

for name in filename: # f = 1, find files only, f = 0,otherwise.

if os.path.isdir(name): ##

file_list.append(name)

name = os.path.abspath(name)

subfile_list = filelist(name,r,f)

for n in range(len(subfile_list)):

subfile_list[n] = ‘\t’+subfile_list[n]

file_list += subfile_list

else:

file_list.append(name)

os.chdir(os.pardir)

return file_list

elif f == 1:

for name in filename:

if os.path.isdir(name):

name = os.path.abspath(name)

subfile_list = filelist(name,r,f)

for n in range(len(subfile_list)):

subfile_list[n] = ‘\t’+subfile_list[n]

file_list += subfile_list

else:

file_list.append(name)

os.chdir(os.pardir)

return file_list

else:

print ‘Error1’

elif r == 0:

if f == 0:

os.chdir(os.pardir)

return filename

elif f == 1:

for name in filename:

if os.path.isfile(name):

file_list.append(name)

os.chdir(os.pardir)

return file_list

else:

print ‘Error2’

else:

print ‘Error3’

”’

f = 0:list all the files and folders

f = 1:list files only

r = 1:list files or folders recursively,all the files and folders in the current direction and subdirection

r = 0:only list files or folders in the current direction,not recursively

as for RE to match certern file or dirction,you can write yourself, it is easier than the function above.Just use RE to match the result,if match,print;else,pass

“””

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/249396.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝的头像小蓝
上一篇 2024-12-12 17:11
下一篇 2024-12-12 17:11

相关推荐

  • 如何查看Anaconda中Python路径

    对Anaconda中Python路径即conda环境的查看进行详细的阐述。 一、使用命令行查看 1、在Windows系统中,可以使用命令提示符(cmd)或者Anaconda Pro…

    编程 2025-04-29
  • Python列表中负数的个数

    Python列表是一个有序的集合,可以存储多个不同类型的元素。而负数是指小于0的整数。在Python列表中,我们想要找到负数的个数,可以通过以下几个方面进行实现。 一、使用循环遍历…

    编程 2025-04-29
  • Python周杰伦代码用法介绍

    本文将从多个方面对Python周杰伦代码进行详细的阐述。 一、代码介绍 from urllib.request import urlopen from bs4 import Bea…

    编程 2025-04-29
  • Python计算阳历日期对应周几

    本文介绍如何通过Python计算任意阳历日期对应周几。 一、获取日期 获取日期可以通过Python内置的模块datetime实现,示例代码如下: from datetime imp…

    编程 2025-04-29
  • Python中引入上一级目录中函数

    Python中经常需要调用其他文件夹中的模块或函数,其中一个常见的操作是引入上一级目录中的函数。在此,我们将从多个角度详细解释如何在Python中引入上一级目录的函数。 一、加入环…

    编程 2025-04-29
  • python强行终止程序快捷键

    本文将从多个方面对python强行终止程序快捷键进行详细阐述,并提供相应代码示例。 一、Ctrl+C快捷键 Ctrl+C快捷键是在终端中经常用来强行终止运行的程序。当你在终端中运行…

    编程 2025-04-29
  • Python字典去重复工具

    使用Python语言编写字典去重复工具,可帮助用户快速去重复。 一、字典去重复工具的需求 在使用Python编写程序时,我们经常需要处理数据文件,其中包含了大量的重复数据。为了方便…

    编程 2025-04-29
  • 蝴蝶优化算法Python版

    蝴蝶优化算法是一种基于仿生学的优化算法,模仿自然界中的蝴蝶进行搜索。它可以应用于多个领域的优化问题,包括数学优化、工程问题、机器学习等。本文将从多个方面对蝴蝶优化算法Python版…

    编程 2025-04-29
  • Python程序需要编译才能执行

    Python 被广泛应用于数据分析、人工智能、科学计算等领域,它的灵活性和简单易学的性质使得越来越多的人喜欢使用 Python 进行编程。然而,在 Python 中程序执行的方式不…

    编程 2025-04-29
  • Python清华镜像下载

    Python清华镜像是一个高质量的Python开发资源镜像站,提供了Python及其相关的开发工具、框架和文档的下载服务。本文将从以下几个方面对Python清华镜像下载进行详细的阐…

    编程 2025-04-29

发表回复

登录后才能评论