Marsellus Wallace
Marsellus Wallace

Reputation: 18611

weird no such file or directory in python

I'm new to python and the following piece of code is driving me crazy. It lists the files in a directory and for each file does some stuff. I get a IOError: [Errno2] No such file or directory: my_file_that_is_actually_there!

def loadFile(aFile):
  f_gz = gzip.open(aFile, 'rb')
  data = f_gz.read()
  #do some stuff...
  f_gz.close()
  return data

def main():
  inputFolder = '../myFolder/'
  for aFile in os.listdir(inputFolder):
    data = loadFile(aFile)
    #do some more stuff

The file exists and it's not corrupted. I do not understand how it's possible that python first finds the file when it checks the content of myFolder, and then it cannot find itanymore... This happens on the second iteration of my for loop only with any files.

NOTE: Why does this exception happen ONLY at the second iteration of the loop?? The first file in the folder is found and opened without any issues...

Upvotes: 0

Views: 1164

Answers (1)

Lev Levitsky
Lev Levitsky

Reputation: 65851

This is because open receives the local name (returned from os.listdir). It doesn't know that you mean that it should look in ../myFolder. So it receives a relative path and applies it to the current dir. To fix it, try:

data = loadFile(os.path.join(inputFolder, aFile))

Upvotes: 2

Related Questions