当前位置:首页 » 编程语言 » 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)
热点内容
h3c如何查看所有配置 发布:2024-05-04 05:26:39 浏览:491
java统计字符串中字母个数 发布:2024-05-04 05:22:58 浏览:886
throwablejava 发布:2024-05-04 05:22:56 浏览:790
IP和服务器可以分开架设吗 发布:2024-05-04 05:17:48 浏览:26
ip提取源码 发布:2024-05-04 05:01:42 浏览:763
驾校报名了密码是什么 发布:2024-05-04 04:49:02 浏览:610
安卓加密的rar软件 发布:2024-05-04 04:18:30 浏览:606
聚会编程题 发布:2024-05-04 04:02:41 浏览:405
我的世界服务器自动扫地 发布:2024-05-04 03:48:41 浏览:612
4500能配什么电脑配置 发布:2024-05-04 03:22:29 浏览:592