python在文件中读取指定的字符串(python读取文件中指定内容)
python 文本文件中查找指定的字符串
编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出绝对路径。
import os
class SearchFile(object):
def __init__(self,path='.'):
self._path=path
self.abspath=os.path.abspath(self._path) # 默认当前目录
def findfile(self,keyword,root):
filelist=[]
for root,dirs,files in os.walk(root):
for name in files:
fitfile=filelist.append(os.path.join(root, name))
#print(fitfile)
print(os.path.join(root, name))
#print(filelist)
print('...........................................')
for i in filelist:
if os.path.isfile(i):
#print(i)
if keyword in os.path.split(i)[1]:
print('yes!',i) # 绝对路径
#else:
#print('......no keyword!')
def __call__(self):
while True:
workpath=input('Do you want to work under the current folder? Y/N:')
if(workpath == ''):
break
if workpath=='y' or workpath=='Y':
root=self.abspath # 把当前工作目录作为工作目录
print('当前工作目录:',root)
dirlist=os.listdir() # 列出工作目录下的文件和目录
print(dirlist)
else:
root=input('please enter the working directory:')
print('当前工作目录:',root)
keyword=input('the keyword you want to find:')
if(keyword==''):
break
self.findfile(keyword,root) # 查找带指定字符的文件
if __name__ == '__main__':
search = SearchFile()
search()
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')forLinfile_object]
如何用Python语言实现在一个文件中查找特定的字符串
targetstr 为特定字符串
filename为文件名
with open(filename,'r')as fp:
for line in fp:
if targetstr in line:
print line
这样就找到特定字符串所在的行内容了
Python:怎样将txt文件读取到一个字符串里?
1、首先在vscode里面添加了Python文件和用于读取的文本文件。
2、然后在txt文件写上一些内容用于待会的内容读取,随便写上即可。
3、此外还必须要导入os文件,这样才可调用os中的一些文件操作方法。
4、然后打开要进行读取内容的文件,并且把读取到的内容数据复制给了字符串。
5、然后把字符串打印即可把内容给展现出来,方便查阅了。
6、接着运行jy.py文件,这样就会开始读取,打印内容。
7、如图,可以看到txt文件的内容真的被读取到了。
python 怎样在文件中查找指定的字符串
第一种情况:在python编辑器中找一个字符串string
ctrl+f
第二种情况:判断元组或列表内是否包含字符串:string in list