我想从多个文件中搜索一个字符串
我尝试了:
import os
path= 'sample1/nvram2/logs'
all_files=os.listdir(path)
for my_file1 in all_files:
print(my_file1)
with open(my_file1, 'r') as my_file2:
print(my_file2)
for line in my_file2:
if 'string' in line:
print(my_file2)
输出:
^{pr2}$但是文件wen dang.txt存在于C:\Users\user1\scripts\sample1\nvram2\logs中
为什么错误显示没有这样的文件或目录?在
使用glob:
当我使用all_files=glob.glob(path)
而不是all_files=os.listdir(path)
时,显示了以下错误
C:\Users\user1\scripts>python search_string_3.py
sample1/nvram2/logs
Traceback (most recent call last):
File "search_string_3.py", line 7, in <module>
with open(my_file1, 'r') as my_file2:
PermissionError: [Errno 13] Permission denied: 'sample1/nvram2/logs'
由于文件
abcd.txt
存在于C:\Users\user1\scripts\sample1\nvram2\logs
中,并且该路径不是您的工作目录,因此您必须将其添加到sys.path
中你猜到了第一个问题。将目录与文件名连接可以解决此问题。A classic:
如果你没有尝试用
^{pr2}$glob
做些什么,我就不想回答了。现在:由于
path
是一个目录,glob
将其作为自身进行计算(得到一个包含一个元素的列表:[path]
)。您需要添加通配符:glob
的另一个问题是,如果目录(或模式)与任何内容不匹配,则不会出现任何错误。它什么都不做。。。os.listdir
版本至少崩溃。在在打开之前还要测试它是否是一个文件(在两种情况下),因为尝试打开目录会导致I/O异常:
简而言之,
os.path
包是您在操作文件时的朋友。在相关问题 更多 >
编程相关推荐