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

2024-09-27 21:27:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我尝试了:

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'

Tags: 文件pathinstringosmylinefiles
2条回答

由于文件abcd.txt存在于C:\Users\user1\scripts\sample1\nvram2\logs中,并且该路径不是您的工作目录,因此您必须将其添加到sys.path

import os, sys
path= 'sample1/nvram2/logs'
sys.path.append(path)


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)

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

with open(os.path.join(path,my_file1), 'r') as my_file2:

如果你没有尝试用glob做些什么,我就不想回答了。现在:

^{pr2}$

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

for x in glob.glob(os.path.join(path,"*")):

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

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

if os.path.isfile(x):
  with open ...

简而言之,os.path包是您在操作文件时的朋友。在

相关问题 更多 >

    热门问题