Skip to content Skip to sidebar Skip to footer

Python Shows No Such File Or Directory Error Though The File Exists

I want to search a string from multiple files What I tried: import os path= 'sample1/nvram2/logs' all_files=os.listdir(path) for my_file1 in all_files: print(my_file1) w

Solution 1:

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:

I wouldn't have cared to answer if you didn't attempt something with glob. Now:

for x in glob.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,"*")):

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.

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:

ifos.path.isfile(x):
  with open ...

In a nutshell os.path package is your friend when manipulating files. Or pathlib if you like object-oriented path manipulations.

Post a Comment for "Python Shows No Such File Or Directory Error Though The File Exists"