用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/zh-hant/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

發表回復

登錄後才能評論