當前位置:首頁 » 編程語言 » python搜索文件內容

python搜索文件內容

發布時間: 2022-09-28 06:27:52

python從文件中查找數據並輸出

#注意,這里的代碼用單空格縮進
importre

#寫上你的文件夾路徑
yourdir=""

keywordA="keywordA"

keywordB="keywordA(d+)"

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

withopen("out.txt","w")asfo:
forfinfiles:
fname=os.path.basename(f)
withopen(f,"r")asfi:
forlineinfi:
ifline.strip():
searchA=re.search(keywordA,line.strip())
ifsearchA:
searchB=re.search(keywordB,line.strip())
ifsearchB:
print(fname,serachB.groups()[0],sep=" ",file=fo)

㈡ 我要用python在txt中查找指定的內容,並且得知該內容在第幾行,該如何做

簡單寫寫,前提是python運行的當前目錄下,有一個xx.txt的文檔。注意else的空格, 不要弄錯了。

s=raw_input('Youfind>>>')
f=open('xx.txt','rb').readlines()
foriinrange(len(f)):
ifsinf[i]:
print'line:',i+1
break
else:
print'sorry!'

㈢ python怎麼讀取文件名的內容

python讀取文件內容的方法:
一.最方便的方法是一次性讀取文件中的所有內容並放置到一個大字元串中:
all_the_text = open('thefile.txt').read( )
# 文本文件中的所有文本
all_the_data = open('abinfile','rb').read( )
# 二進制文件中的所有數據
為了安全起見,最好還是給打開的文件對象指定一個名字,這樣在完成操作之後可以迅速關閉文件,防止一些無用的文件對象佔用內存。舉個例子,對文本文件讀取:
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
不一定要在這里用Try/finally語句,但是用了效果更好,因為它可以保證文件對象被關閉,即使在讀取中發生了嚴重錯誤。
二.最簡單、最快,也最具Python風格的方法是逐行讀取文本文件內容,並將讀取的數據放置到一個字元串列表中:
list_of_all_the_lines = file_object.readlines( )
這樣讀出的每行文本末尾都帶有"\n"符號;如果你不想這樣,還有另一個替代的辦法,比如:
list_of_all_the_lines = file_object.read( ).splitlines( )
list_of_all_the_lines = file_object.read( ).split('\n')
list_of_all_the_lines = [L.rstrip('\n') for L in file_object]
最簡單最快的逐行處理文本文件的方法是,用一個簡單的for循環語句:
for line in file_object:
process line
這種方法同樣會在每行末尾留下"\n"符號;可以在for循環的主體部分加一句:
lineline = line.rstrip('\n')
或者,你想去除每行的末尾的空白符(不只是'\n'\),常見的辦法是:
lineline = line.rstrip( )

㈣ 如何用Python os.path.walk方法遍歷搜索文件內容的操作詳解

importos,sys
#代碼中需要用到的方法模塊導入


listonly=False

skipexts=['.gif','.exe','.pyc','.o','.a','.dll','.lib','.pdb','.mdb']#ignorebinaryfiles


defvisitfile(fname,searchKey):
globalfcount,vcount
try:
ifnotlistonly:
ifos.path.splitext(fname)[1]inskipexts:
pass
elifopen(fname).read().find(searchKey)!=-1:
print'%shas%s'%(fname,searchKey)
fcount+=1
except:pass
vcount+=1

#www.iplaypython.com

defvisitor(args,directoryName,filesInDirectory):
forfnameinfilesInDirectory:
fpath=os.path.join(directoryName,fname)
ifnotos.path.isdir(fpath):
visitfile(fpath,args)


defsearcher(startdir,searchkey):
globalfcount,vcount
fcount=vcount=0
os.path.walk(startdir,visitor,searchkey)


if__name__=='__main__':
root=raw_input("typerootdirectory:")
key=raw_input("typekey:")
searcher(root,key)
print'Foundin%dfiles,visited%d'%(fcount,vcount)

㈤ python讀取txt文件,查找到指定內容,並做出修改

def modifyip(tfile,sstr,rstr):

try:

lines=open(tfile,'r').readlines()

flen=len(lines)-1

for i in range(flen):

if sstr in lines[i]:

lines[i]=lines[i].replace(sstr,rstr)

open(tfile,'w').writelines(lines)

except Exception,e:

print e


modifyip('a.txt','a','A')


㈥ 用python搜索文件夾內所有文件,並且根據名字打開其他文檔

importglob,os,re

path_a='e:\A'
path_b='e:\B'

a_files=glob.glob('%s\*'%path_a)
b_files=glob.glob('%s\*'%path_b)

forfina_files:
file_name=os.path.basename(f)
file_name_in_folder_b=re.subn(ur'd{8}_d{2}_d{2}_d{2}_','',file_name)
full_path='%s\%s'%(path_b,file_name_in_folder_b)
iffull_pathinb_files:
file_in_b=open(full_path,'r')

㈦ python查找txt文件中關鍵字

偽代碼:

1、遍歷文件夾下所有txt文件

rootdir='/path/to/xx/dir'#文件夾路徑
forparent,dirnames,filenamesinos.walk(rootdir):
forfilenameinfilenames:

2、讀取txt文件里的內容,通過正則表達式把txt里多篇文章拆分開來。得到一個列表:['{xx1}##NO','{xx2}','{xx3}##NO']

3、把上面得到的list寫到一個新的臨時文件里,比如:xx_tmp.txt,然後:shutil.move('xx_tmp.txt','xx.txt')覆蓋掉原來的文件

㈧ 用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
"""

㈨ python怎麼兩兩查找多個文件相同內容

可以用 difflib庫,下面給一個例子,具體需求自己研究
假如在同一個目錄下有a.txt, b.txt 兩個文本文件
a.txt 內容是
aaa
bbb

b.txt內容是
aaa
ccc

import difflib

a = open('a.txt', 'U').readlines()
b = open('b.txt', 'U').readlines()
diff = difflib.ndiff(a, b)

sys.stdout.writelines(diff)

結果是:
aaa
- bbb+ ccc

㈩ 跪求!用python對文本文件的內容查找

python3.3代碼

importsys
reader=open('scores.txt')
line=reader.readline()#讀取第一行數據
scores=[]#放分數值的數值
stander=0#及格人數
whileline!=''andline!=None:#循環讀取數據行
tempScore=line.split('')[1].replace(' ','')#將姓名和成績分開,並取分數
scores.append(tempScore);#將得到的分數添加到數組中
iffloat(tempScore)>=60:#記錄大於60分的成績
stander+=1
line=reader.readline()
reader.close()
print(scores)
print(stander)
熱點內容
浙江萬里的伺服器地址 發布:2024-04-20 21:16:59 瀏覽:406
ndklinux下載 發布:2024-04-20 21:05:22 瀏覽:565
王者榮耀解壓資源包97 發布:2024-04-20 20:46:10 瀏覽:396
蘋果手機沒有密碼怎麼打開 發布:2024-04-20 20:45:25 瀏覽:92
如何用濃硝酸配置百分之2的硝酸 發布:2024-04-20 20:44:39 瀏覽:796
微信商城java源碼下載 發布:2024-04-20 20:27:35 瀏覽:121
用友軟體sql 發布:2024-04-20 20:10:01 瀏覽:933
python倒著循環 發布:2024-04-20 20:09:52 瀏覽:759
雲伺服器遠程電腦版 發布:2024-04-20 20:09:12 瀏覽:259
ps資料庫 發布:2024-04-20 19:52:43 瀏覽:522