user3702643
user3702643

Reputation: 1495

Python: Why do I keep getting no such file or directory?

I have this piece of code that scans a directory and reads and prints each file in the directory one by one (HTML files). But each time I try to run this code, I get IOError: [Errno 2] No such file or directory: 'index.html' (index.html is the first file in the folder) Can anyone help me out with this?

files = os.listdir('/Users/folder/')
print files
for name in files:  
    try:
        with open(name) as f:  
            sys.stdout.write(f.read())
    except IOError as exc:
        if exc.errno != errno.EISDIR:  
            raise

Upvotes: 0

Views: 980

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174624

You can use glob, and isfile:

import glob
import os

for f in glob.glob('/Users/folder/*.html'):
  if os.path.isfile(f):
      with open(f, 'r') as the_file:
          contents = the_file.read()
          # do stuff

If you give glob the entire path, the results will have the entire path included; which is why you don't need os.path.join

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 113955

You get that error because os.listdir returns a list of the filenames in the given directory. To access those files, you need to access them from the given directory; else python will try to find the files in the current working directory.

Here's how you can fix your code:

mainDir = '/Users/folder/'
files = os.listdir(mainDir)
for name in files:
    fname = os.path.join(mainDir, name)  # this is the part you're missing
    try:
        with open(fname) as f:
            contents = f.read()  # do regex matching against `contents` now
    except IOError as exc:
        if exc.errno != errno.EISDIR:  
            raise

Upvotes: 2

Related Questions