您的位置:

用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

"""