本文目錄一覽:
- 1、如何用python查詢文件路勁
- 2、如何用Python實現在文件夾下查找一個關鍵詞
- 3、python從文件中查找數據並輸出
- 4、如何用Python語言實現在一個文件中查找特定的字符串?
- 5、請問如何用python實現查找指定文件?
- 6、用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