问题描述
我想从多个文件中搜索一个字符串
I want to search a string from multiple files
我的尝试:
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
But file abcd.txt is present in C:\Users\user1\scripts\sample1\nvram2\logs
为什么错误显示没有这样的文件或目录?
Why the Error shows that No such file or directory?
使用 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'
推荐答案
你发现/猜到了第一个问题.用文件名加入目录可以解决它.经典:
you figured out/guessed the first issue. Joining the directory with the filename solves it. A classic:
with open(os.path.join(path,my_file1), 'r') as my_file2:
如果您不尝试使用 glob
进行某些操作,我就不会在意回答.现在:
I wouldn't have cared to answer if you didn't attempt something with glob
. Now:
for x in glob.glob(path):
因为 path
是一个目录,glob
将它作为自身进行评估(你得到一个包含一个元素的列表:[path]
).您需要添加通配符:
since path
is a directory, glob
evaluates it as itself (you get a list with one element: [path]
). You need to add a wildcard:
for x in glob.glob(os.path.join(path,"*")):
glob
的另一个问题是,如果目录(或模式)与任何内容都不匹配,您不会收到任何错误.它什么都不做……os.listdir
版本至少崩溃了.
The other issue with glob
is that if the directory (or the pattern) doesn't match anything you're not getting any error. It just does nothing... The os.listdir
version crashes at least.
并在打开之前测试它是否是文件(在两种情况下),因为尝试打开目录会导致 I/O 异常:
and also test if it's a file before opening (in both cases) because attempting to open a directory results in an I/O exception:
if os.path.isfile(x):
with open ...
简而言之 os.path
包是您操作文件时的朋友.或者 pathlib
如果你喜欢面向对象的路径操作.
In a nutshell os.path
package is your friend when manipulating files. Or pathlib
if you like object-oriented path manipulations.
这篇关于Python 显示 No such file or directory 错误,尽管文件存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!