【问题标题】:Python shows No such file or directory Error though the file existsPython显示没有这样的文件或目录错误,尽管文件存在
【发布时间】:2018-11-14 09:11:53
【问题描述】:

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

我尝试了什么:

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'

但是文件 abcd.txt 存在于 C:\Users\user1\scripts\sample1\nvram2\logs

为什么错误显示没有这样的文件或目录?

使用全局:

当我使用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'

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您已经猜到/猜到了第一个问题。用文件名加入目录可以解决它。 A classic:

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

    如果您不尝试使用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 ...
    

    简而言之,os.path 包是您操作文件时的朋友。或者pathlib,如果你喜欢面向对象的路径操作。

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      • 2022-10-21
      • 2021-10-31
      相关资源
      最近更新 更多