我想在文件夹中的许多文件中搜索“word”。
我已经:
route=os.listdir("/home/new")
for file in route:
这不起作用:
f = open ('' , 'r')
for line in f :
我试过了:
for file in route:
f = open(file, 'r')
for line in f:
if word in line:
print(file)
break
但我有一个错误:
f=open( file ,'r')
IOError: [Errno 2] No such file or directory: file.txt
当我删除file.txt,下一个文件时,我收到同样的错误。
答案 0 :(得分:0)
for file in filelist:
f = open(file,"r")
data = f.read()
rows = data.split("\n")
count = 0
full_data = []
for row in rows:
split_row = row.split(",")
full_data.append(split_row)
for each in full_data:
if re.search("word", each) is not None:
count += 1
这样的事情,虽然你的问题根本不是关于你是否想要计算,返回找到单词的地方,将单词更改为某些内容等等,所以请随意根据需要进行编辑
(此代码适用于.csv,你可以告诉)
答案 1 :(得分:0)
os.listdir
only returns the file names,而非合格路径。为了实现这一目标,您的open
需要打开合格路径(使用os.path.join("/home/new", file)
构建),而不仅仅是file
。
答案 2 :(得分:0)
这些方面的内容怎么样?
import os
folderpath = "/.../.../foldertosearch"
word = 'giraffe'
for(path, dirs, files) in os.walk(folderpath, topdown=True):
for filename in files:
filepath = os.path.join(path, filename)
with open(filepath, 'r') as currentfile:
for line in currentfile:
if word in line:
print(
'Found the word in ' + filename + ' in line ' +
line
)
答案 3 :(得分:-1)
你已经把它放下了:
pyplot.hexbin