Python没有显示这样的文件或目录错误,尽管文件存在

Python没有显示这样的文件或目录错误,尽管文件存在,python,python-3.x,Python,Python 3.x,我想从多个文件中搜索字符串 我的尝试: 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 'stri

我想从多个文件中搜索字符串

我的尝试:

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)
C:\Users\user1\scripts>python search_string_3.py
abcd.txt
Traceback (most recent call last):
  File "search_string_3.py", line 6, in <module>
    with open(my_file1, 'r') as my_file2:
FileNotFoundError: [Errno 2] No such file or directory: 'abcd.txt'
输出:

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)
C:\Users\user1\scripts>python search_string_3.py
abcd.txt
Traceback (most recent call last):
  File "search_string_3.py", line 6, in <module>
    with open(my_file1, 'r') as my_file2:
FileNotFoundError: [Errno 2] No such file or directory: 'abcd.txt'

你猜出了第一个问题。将目录与文件名连接可以解决此问题:

如果你不尝试使用
glob
,我就不想回答了。现在:

for x in glob.glob(path):
由于
path
是一个目录,
glob
将其作为自身进行计算(您将得到一个包含一个元素的列表:
[path]
)。您需要添加通配符:

for x in glob.glob(os.path.join(path,"*")):
glob
的另一个问题是,如果目录(或模式)与任何内容都不匹配,则不会出现任何错误。它什么都不做。。。
os.listdir
版本至少崩溃

并在打开之前测试它是否是文件(在这两种情况下),因为尝试打开目录会导致I/O异常:

if os.path.isfile(x):
  with open ...
简而言之,在操作文件时,path是您的朋友。或者,如果您喜欢面向对象的路径操作